package com.pi.pro.xcmg.am.was.fac.service;




import com.fasterxml.jackson.annotation.JsonView;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.pi.common.CodesConstants;
import com.pi.common.utils.MathUtils;
import com.pi.common.utils.StringUtils;
import com.pi.common.utils.TextUtils;
import com.pi.framework.core.bean.PageResult;
import com.pi.framework.core.util.DateUtils;
import com.pi.framework.core.util.SecurityUtils;
import com.pi.pro.xcmg.am.common.XcmgAmConstants;
import com.pi.pro.xcmg.am.common.XcmgAmSupport;
import com.pi.pro.xcmg.am.common.vo.act.*;
import com.pi.pro.xcmg.am.common.vo.edi.KitDocumentLineReplyData;
import com.pi.pro.xcmg.am.common.vo.edi.KitDocumentReplyData;
import com.pi.pro.xcmg.am.common.vo.edi.LedMessageData;
import com.pi.pro.xcmg.am.common.vo.edi.XwmsInventoryLineDto;
import com.pi.pro.xcmg.am.was.edi.infor.common.InforWasExchangeSupport;
import com.pi.pro.xcmg.am.was.edi.infor.common.InforWasXcmgExchangeConstants;
import com.pi.pro.xcmg.am.was.edi.infor.dto.reply.FuncReplyData;
import com.pi.pro.xcmg.am.was.edi.infor.dto.reply.StorageLineResultDto;
import com.pi.pro.xcmg.am.was.edi.infor.dto.reply.TaskReportResultDto;
import com.pi.pro.xcmg.am.was.edi.infor.dto.req.StorageQueryData;
import com.pi.pro.xcmg.am.was.edi.infor.dto.req.TaskOrderDto;
import com.pi.pro.xcmg.am.was.edi.infor.dto.req.TaskReportData;
import com.pi.pro.xcmg.am.was.edi.mes.common.MesWasExchangeSupport;
import com.pi.pro.xcmg.am.was.edi.mes.common.MesWasXcmgExchangeConstants;
import com.pi.pro.xcmg.am.was.edi.sap.common.SapWasXcmgExchangeConstants;
import com.pi.pro.xcmg.am.was.edi.sap.common.SapWasXcmgExchangeSupport;
import com.pi.pro.xcmg.am.was.edi.sap.dto.reply.DeliveryNoteData;
import com.pi.pro.xcmg.am.was.edi.sap.dto.reply.DeliveryNoteTransReplyData;
import com.pi.pro.xcmg.am.was.edi.sap.dto.req.DeliveryNoteTransData;
import com.pi.pro.xcmg.am.was.edi.wcs.common.WcsWasExchangeSupport;
import com.pi.pro.xcmg.am.was.edi.wcs.common.WcsWasXcmgExchangeConstants;
import com.pi.pro.xcmg.am.was.edi.wcs.dto.CommonResultData;
import com.pi.pro.xcmg.am.was.fac.handler.WorkDataHolders;
import com.pi.wms.base.LotattrAware;
import com.pi.wms.common.WmsConstants;
import com.pi.wms.dto.act.*;
import com.pi.wms.dto.base.LocationLineDto;
import com.pi.wms.dto.doc.DocumentActionDto;
import com.pi.wms.dto.inventory.InventoryChangeActionDto;
import com.pi.wms.entity.*;
import com.pi.wms.fac.AdvanceStorageBuilder;
import com.pi.wms.fac.LocationResolver;
import com.pi.wms.fac.TransBuilder;
import com.pi.wms.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.datatables.mapping.DataTablesOutput;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Slf4j
@Service
public class WasCustomWorkService {


    @Autowired
    private MaterialService materialService;

    @Autowired
    private DivisionService divisionService;

    @Autowired
    private LogisticsSeqService seqService;

    @Autowired
    private LocationService locationService;

    @Autowired
    private ZoneService zoneService;

    @Autowired
    private AsnService asnService;

    @Autowired
    private AsnDetailsService asnDetailsService;

    @Autowired
    private SoService soService;

    @Autowired
    private SoDetailsService soDetailsService;

    @Autowired
    private WaveService waveService;

    @Autowired
    private InventoryDetailsService inventoryService;

    @Autowired
    private InventoryLotattrService lotattrService;

    @Autowired
    private InventoryLotnumService lotnumService;

    @Autowired
    private CoService coService;

    @Autowired
    private CoDetailsService coDetailsService;

    @Autowired
    private PalletizeService palletizeService;

    @Autowired
    private ReceiveService receiveService;

    @Autowired
    private AllocationService allocationService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private TransService transService;

    @Autowired
    private PrintTaskService printTaskService;

    @Autowired
    private EdiTransactionService ediTransactionService;

    @Autowired
    private LocationResolver locationResolver;

    @Autowired
    private StorageService storageService;

    @Autowired
    private MesKitDocklineService mesKitDocklineService;

    @Autowired
    private CustDyncdataQueryService dyncdataQueryService;

    @Autowired
    private InforCommonWorkService inforCommonWorkService;

    @Autowired
    private WcsCustomWorkService wcsCustomWorkService;

    @Autowired
    private WcsCustomWorkApiService wcsCustomWorkApiService;

    @Autowired
    private LedMessageService ledMessageService;

    @Autowired
    private MesCustomWorkService mesCustomWorkService;

    @Autowired
    private AdvanceStorageBuilder storageBuilder;

    @Autowired
    private TransBuilder transBuilder;


    @PersistenceContext
    protected EntityManager entityManager;


    //严格校验模式
    //
    private String waveCreateStrictMode = CodesConstants.COMMON_FLAG_YES;
    //盘点调账模式
    private String countTransferMode = XcmgAmConstants.COUNT_TRANSFER_MODE_COUNT_MAKE_CHANGE;

    private Map<Long, LocationLineDto> srmPickLocationMap=new HashedMap();

    //
    private Cache<Long, String> locationZoneCache= CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.MINUTES).build();
    //TODO:HU/202507
    //临时方案,后续调整PDA
    private Cache<Long, String> countTaskCheckedCache= CacheBuilder.newBuilder().expireAfterWrite(20, TimeUnit.SECONDS).build();




/**==================================================================================================================**/
// ---- CUSTOM/COMMON
/**==================================================================================================================**/

    public String populateWasLotnumber(XwmsInventoryLineDto palletizeData){
        String  m = "";
        if (StringUtils.isNullOrBlank(palletizeData.getLotattr05())){
            palletizeData.setLotattr05(DateUtils.format(new Date(), "yyyy"));
        }
        return m;
    }

    public String populateWasLotnumber(PalletizeChangeData palletizeData){
        String  m = "";
        if (StringUtils.isNullOrBlank(palletizeData.getLotattr05())){
            palletizeData.setLotattr05(DateUtils.format(new Date(), "yyyy"));
        }
        return m;
    }

    public String xwmsWarehouseCodeOf(String divisionCode){
        if (StringUtils.isNullOrBlank(divisionCode)){
            divisionCode=XcmgAmConstants.DIVISION_WH101_CODE;
        }
        if (XcmgAmConstants.DIVISION_WH101_CODE.equalsIgnoreCase(divisionCode)){
            return InforWasXcmgExchangeConstants.INFOR_MAP_WH101_WAREHOUSER_ID;
        }
        return InforWasXcmgExchangeConstants.INFOR_MAP_WH101_WAREHOUSER_ID;
    }


    //提取码盘数据到库存
    public String syncPalletizeDataToStorage(TwtActPalletizeList palletize, TwaInventoryDetails storage){
        String m = "";
        if (palletize==null){
            return m;
        }
        if (storage==null){
            return m;
        }
        //PO//
        if (!StringUtils.isNullOrBlank(palletize.getDocType())) {
            storage.setReserveCode(palletize.getDocType().trim());
        }
        //WBS
        if (!StringUtils.isNullOrBlank(palletize.getRefNumber())) {
            storage.setReserveDocNumber(palletize.getRefNumber().trim());
        }

        if (!StringUtils.isNullOrBlank(palletize.getUdf03())){
            storage.setUdf03(palletize.getUdf03().trim());
        }
        if (!StringUtils.isNullOrBlank(palletize.getUdf04())){
            storage.setUdf04(palletize.getUdf04().trim());
        }
        if (!StringUtils.isNullOrBlank(palletize.getUdf05())){
            storage.setUdf05(palletize.getUdf05().trim());
        }
        if (!StringUtils.isNullOrBlank(palletize.getUdf06())){
            storage.setUdf06(palletize.getUdf06().trim());
        }
        if (!StringUtils.isNullOrBlank(palletize.getUdf07())){
            storage.setUdf07(palletize.getUdf07().trim());
        }
        if (!StringUtils.isNullOrBlank(palletize.getUdf08())){
            storage.setUdf08(palletize.getUdf08().trim());
        }
        if (!StringUtils.isNullOrBlank(palletize.getNotes())){
            storage.setNotes(palletize.getNotes().trim());
        }
        return m;
    }

    //提取码盘数据到拣货任务
    public String syncDocumentDataToPickTask(TwaDocWaveHeader header, TwaDocWaveDetails details, TwtActTaskList task){
        String m = "";
        if (header==null){
            return m;
        }
        if (details==null){
            return m;
        }
        if (task==null){
            return m;
        }
        if (!StringUtils.isNullOrBlank(header.getCategory())){
            task.setCategory(header.getCategory());
        }
        if (!StringUtils.isNullOrBlank(header.getCreateSource())){
            task.setTaskSchema(header.getCreateSource());
        }
        if (!StringUtils.isNullOrBlank(header.getWorkHandleCode())){
            task.setTaskFeature(header.getWorkHandleCode().trim());
        }
        if (!StringUtils.isNullOrBlank(details.getDEdi13())){
            task.setUdf09(details.getDEdi13().trim());
        }
        LocationLineDto loc=null;
        try{
            if (!StringUtils.isNullOrBlank(header.getPickLocationCode())){
                loc=this.locationResolver.lookup(header.getDivisionId(), header.getPickLocationCode());
                if (loc!=null){
                    task.setToLocId(loc.getLocationId());
                    task.setToLocSeq(loc.getPkSeqCode());
                    task.setPlantoLocId(task.getToLocId());
                    task.setPlantoLocSeq(task.getToLocSeq());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return m;
    }

    //提取码盘数据到库存
    public String syncDocumentDataToTrans(TwaDocAsnHeader asnHeader, TwaDocAsnDetails asnDetails,
                                          TwaDocSoHeader soHeader, TwaDocSoDetails soDetails, TwtActAllocationList allocation, TwtActTransList trans){
        String m = "";
        if (trans==null){
            return m;
        }

        if (WmsConstants.TRANS_TYPE_RECEIVE.equalsIgnoreCase(trans.getType())){
            if (asnDetails!=null){
                //1.3 IN/OUT/MOVE
                trans.setUdf16(InforWasXcmgExchangeConstants.TASK_TYPE_PUTAWAY);
                //1.4 TASK-CODE
                trans.setCallNumber(String.valueOf(trans.getRefTaskId()));
                //1.5 X-LOTNO
                trans.setUdf17(asnDetails.getUdf07());
            }
            if (asnHeader!=null){
                //1.1 PO/MA
                if (!StringUtils.isNullOrBlank(asnHeader.getCategory())){
                    trans.setCategory(asnHeader.getCategory());
                }
                //1.2 X-WMS
                trans.setUdf11(asnHeader.getCreateSource());
                if (!StringUtils.isNullOrBlank(asnHeader.getCreateSource())){
                    trans.setUdf02(asnHeader.getCreateSource());
                }
            }
        }
        if (WmsConstants.TRANS_TYPE_MOVE.equalsIgnoreCase(trans.getType())){
            //
        }
        if (WmsConstants.TRANS_TYPE_SHIP.equalsIgnoreCase(trans.getType())){
            if (allocation!=null){
                if (trans.getRefTaskId()==null){
                    trans.setRefTaskId(allocation.getId());
                }else {
                    if (!StringUtils.isNullOrBlank(trans.getRefTaskNumber())){
                        trans.setRefTaskId(allocation.getId());
                    }else {
                        //
                    }
                }
            }
            if (soDetails!=null){
                //1.3 IN/OUT/MOVE
                trans.setUdf16(soDetails.getDEdi06());
                //1.4 TASK-CODE
                trans.setCallNumber(soDetails.getDeliveryMode());
                //1.5 X-LOTNO
                trans.setUdf17(soDetails.getDEdi07());
            }
            if (soHeader!=null){
                //1.1 PO/MA
                if (!StringUtils.isNullOrBlank(soHeader.getCategory())){
                    trans.setCategory(soHeader.getCategory());
                }
                //1.2 X-WMS
                trans.setUdf11(soHeader.getCreateSource());
                if (!StringUtils.isNullOrBlank(soHeader.getCreateSource())){
                    trans.setUdf02(soHeader.getCreateSource());
                }
            }
        }
        return m;
    }

    //
    public String defLotnumber(){
        return DateUtils.format(new Date(), "yyyy");
    }

/**==================================================================================================================**/
// ---- COMMON/KEY
/**==================================================================================================================**/
    /**
     * 任务完成
     * 隐含:任务为一组/同托
     */
    public String taskFinish(List<TwtActTaskList> tasks, String toLocationCode, String eventSource, TaskActionDto actionDto){
        String m = "";
        if ((tasks==null)||(tasks.size()==0)){
            m="任务为空";
            return m;
        }
        //默认WCS触发
        if (StringUtils.isNullOrBlank(eventSource)){
            eventSource=CodesConstants.SYSTEM_WCS;
        }
        String worker=SecurityUtils.getLoginUsername();
        if ((actionDto!=null) && (StringUtils.isNullOrBlank(actionDto.getWorker()))){
            worker=actionDto.getWorker().trim();
        }

        TwtActTaskList task=null;
        String containnum=null;
        Map<String, List<TwtActTaskList>> ctasksMap=new HashedMap();
        List<TwtActTaskList> ctasks=null;
        for (TwtActTaskList t:tasks){
            if (t==null){
                continue;
            }
            if (this.closed(t)){
                m="任务已经关闭/取消.任务号:"+t.getNumber();
                return m;
            }
            ctasks=ctasksMap.get(t.getFromContainNumber());
            if (ctasks==null){
                ctasks=new ArrayList<>();
                ctasksMap.put(t.getFromContainNumber(), ctasks);
            }
            ctasks.add(t);
            task=t;
        }
        String tasktype=null;
        String taskmode=null;
        Long tolocid=null;
        LocationLineDto toloc=null;
        LocationLineDto checkloc=null;
        TaskChangeActionDto changeActionDto=null;
        boolean checked=false;
        Map<String, String> movecloseStations=null;
        if (!StringUtils.isNullOrBlank(toLocationCode)){
            checkloc=this.locationResolver.lookup(task.getDivisionId(), toLocationCode.trim());
        }
        try{
            //
            for (Map.Entry<String, List<TwtActTaskList>> entry:ctasksMap.entrySet()){
                if (StringUtils.isNullOrBlank(entry.getKey())){
                    continue;
                }
                if ((entry.getValue()==null) || (entry.getValue().size()==0)){
                    continue;
                }
                checked=false;
                task=entry.getValue().get(0);
                tasktype=task.getType();
                taskmode=task.getTaskMode();
                containnum=entry.getKey().trim();
                toloc=checkloc;
                if (toloc==null){
                    tolocid=task.getToLocId();
                    if (task.getPlantoLocId()!=null){
                        tolocid=task.getPlantoLocId();
                    }
                    toloc=this.locationResolver.lookup(tolocid);
                }

                //2.1 PALLET-RECEIVE
                if (WmsConstants.TASK_TYPE_PUTAWAY.equalsIgnoreCase(tasktype)){
                    if ((task.getRefId()!=null) && (XcmgAmConstants.TASK_ACTION_PALLETIZE.equalsIgnoreCase(task.getTaskAction()))){
                        m = this.fullPalletizeReceive(containnum, toloc, actionDto);
                        //
                        m = this.changeAsnHeaderDeliveryStatus(task.getDocId(), entry.getKey(), WmsConstants.ASN_STATUS_CLOSE, actionDto.getWorker());
                        checked=true;
                    }

                }
                if (!checked){
                    changeActionDto=new TaskChangeActionDto();
                    changeActionDto.setBatchnumber(actionDto.getBatchNumber());
                    changeActionDto.setChangetoLocationCode(toloc.getLocationCode());
                    changeActionDto.setWorkMode(actionDto.getWorkMode());
                    changeActionDto.setWorker(actionDto.getWorker());
                }


                //2.2 PUTAWAY
                if  ((!checked) && (WmsConstants.TASK_TYPE_PUTAWAY.equalsIgnoreCase(tasktype))) {
                    m = this.taskService.finish(task, changeActionDto);
                    checked=true;
                }

                //2.3 PICK
                if  ((!checked) && (WmsConstants.TASK_TYPE_PICK.equalsIgnoreCase(tasktype))) {
                    //直接移库
                    if (CodesConstants.SYSTEM_WCS.equalsIgnoreCase(eventSource)) {
                        this.containerFullMove(containnum, toloc, worker);
                        //
                        movecloseStations=XcmgAmSupport.moveCloseStation(this.divisionService.retrieve(toloc.getDivisionId()));
                        if ((movecloseStations!=null) && (movecloseStations.containsKey(toLocationCode))){
                            this.changeTaskStatus(entry.getValue(), WmsConstants.TASK_STATUS_EDI_CLOSE, "", worker);
                        }
                    } else {
                        //暂时不提供完整逻辑：回传XWMS
                        for (TwtActTaskList t1 : entry.getValue()) {
                            if (t1 == null) {
                                continue;
                            }
                            m = this.taskService.finish(t1, this.transBuilder, changeActionDto);
                        }
                    }
                    checked=true;
                }

                //2.4 MOVE
                if  ((!checked) && (WmsConstants.TASK_TYPE_MOVE.equalsIgnoreCase(tasktype))){
                    if (WcsWasXcmgExchangeConstants.RESULT_CODE_RETURN.equalsIgnoreCase(taskmode)){
                        m = this.taskService.finish(task, changeActionDto);
                    }else {
                        //this.changeTaskStatus(entry.getValue(), WmsConstants.TASK_STATUS_CLOSE, "", worker);
                        if (CodesConstants.SYSTEM_WCS.equalsIgnoreCase(eventSource)) {
                            this.containerFullMove(containnum, toloc, worker);
                        }
                        if ((checkloc!=null) && (WmsConstants.LOCATION_TYPE_BIN.equalsIgnoreCase(checkloc.getLocationType()))){
                            this.changeTaskStatus(entry.getValue(), WmsConstants.TASK_STATUS_CLOSE, "", worker);
                        }else {
                            movecloseStations=XcmgAmSupport.moveCloseStation(this.divisionService.retrieve(toloc.getDivisionId()));
                            if ((movecloseStations!=null) && (movecloseStations.containsKey(toLocationCode))){
                                this.changeTaskStatus(entry.getValue(), WmsConstants.TASK_STATUS_CLOSE, "", worker);
                            }
                        }
                    }
                }

                //2.5 COUNT
                if  ((!checked) && (WmsConstants.TASK_TYPE_COUNT.equalsIgnoreCase(tasktype))){
                    if (WcsWasXcmgExchangeConstants.RESULT_CODE_RETURN.equalsIgnoreCase(taskmode)){
                        changeActionDto.setWorkMode(WmsConstants.COUNT_TASK_FIN_MODE_MOVE_COUNT);
                        changeActionDto.setLocationCode(toloc.getLocationCode());
                        m = this.taskService.finish(task, changeActionDto);
                    }else {
                        if (CodesConstants.SYSTEM_WCS.equalsIgnoreCase(eventSource)) {
                            this.containerFullMove(containnum, toloc, worker);
                        }
                    }
                }
            }
        }catch (Exception e){
            m="执行任务完成异常.异常信息:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }



/**==================================================================================================================**/
// ---- INBOUND/PALLETIZE
/**==================================================================================================================**/

    //新增
    public String palletizeCreate(PalletizeChangeData palletizeData, TaskActionDto actionDto) {
        String m = "";

        m = this.palletizeCheck(palletizeData);
        if (!StringUtils.isNullOrBlank(m)){
            return m;
        }
        //
        Long diviosnId=this.divisionService.retrieveOn(palletizeData.getDivisioncode(), XcmgAmConstants.DIVISION_WH101_ID);

        actionDto=this.workAction(actionDto);
        this.defValue(palletizeData, actionDto);
        this.populateWasLotnumber(palletizeData);
        String materialCode=palletizeData.getMaterialcode();
        String containNumber=palletizeData.getContainnumber().trim();
        String traceNumber=palletizeData.getTracenumber().trim();

        TwaDocAsnHeader header=null;
        TwaDocAsnDetails details=null;
        TwtActPalletizeList palletize=null;
        TwmBasMaterial material=null;
        LocationLineDto loc=null;
        List<XwmsInventoryLineDto> xwmslines=null;
        List<XwmsInventoryLineDto> matchlines=null;
        XwmsInventoryLineDto checkline=null;
        BigDecimal total=null;
        BigDecimal qtyopen=null;
        int index=0;
        try{
            //
            xwmslines=this.loadXwmsInventory(palletizeData.getDivisioncode(), materialCode, false, actionDto);
            this.calculateInventoyDataPalletizeQuantity(xwmslines, true);
            matchlines=this.match(xwmslines, palletizeData);
            /**
            palletizes=this.palletizeService.findByTraceNumber(traceNumber);
            if ((palletizes!=null)&&(palletizes.size()>0)){
                m="料箱已经码盘,不能重复码盘.箱码:"+traceNumber;
                return m;
            }
             **/
            //物料核对
            if (!StringUtils.isNullOrBlank(materialCode)){
                material = this.materialService.lookup(palletizeData.getCustomercode(), materialCode);
                if (material==null){
                    m="找不到物料主数据,请确认是否已删除.物料码:"+materialCode;
                    return m;
                }
            }
            //
            loc=this.locationResolver.lookup(XcmgAmConstants.LOCATION_CODE_PA0101);
            if (!StringUtils.isNullOrBlank(palletizeData.getLocationcode())){
                loc=this.locationResolver.lookup(diviosnId, palletizeData.getLocationcode());
            }
            //

            //TODO:HU/202504
            //再次接口数据核对


            //单证核对
            /**
            if (!StringUtils.isNullOrBlank(inventSeqData.getReceiveDocNumber())){
                header=this.asnService.findByDocumentNumber(inventSeqData.getReceiveDocNumber().trim());
                if (header!=null){
                    if (!StringUtils.isNullOrBlank(inventSeqData.getReceiveDocLinenumber())){
                        line=this.asnDetailsService.findByDocumentLine(header.getId(), inventSeqData.getReceiveDocLinenumber().trim());
                    }else {
                        lines=this.asnDetailsService.findByMaterial(header.getId(), inventSeqData.getMaterialId());
                        if ((lines!=null) && (lines.size()>0)){
                            line=lines.get(0);
                        }
                    }
                }
            }
            **/
            //生成入库单
            header=this.takeAsnHeader(diviosnId, palletizeData, material, actionDto.getWorker());
            if (header==null){
                m="创建入库单失败.托盘码:"+palletize.getContainNumber();
                return m;
            }
            if ((header.isNew()) || (header.getId()==null)){
                header = this.asnService.save(header);
                WorkDataHolders.get(diviosnId).savePalletContainnumberWithAsn(palletizeData.getContainnumber(), header.getId());
            }
            //
            if ((matchlines==null) || (matchlines.size()<=1)){
                details=this.createAsnLine(header, palletizeData, material, loc, actionDto);
                if (details==null){
                    m="创建入库单明细行失败.托盘码:"+palletize.getContainNumber();
                    return m;
                }
                this.asnDetailsService.save(details);
                //3. 生成码盘数据
                //palletize=this.createPalletizeData(palletizeData, material, actionDto);
                palletize=this.createPalletizeData(palletizeData, header, details, material, actionDto);
                if (palletize!=null){
                    this.palletizeService.save(palletize);
                }
            }
            if ((matchlines!=null) && (matchlines.size()>1)){
                total=palletizeData.getQuantity();
                checkline=matchlines.get(index);
                while(total.compareTo(BigDecimal.ZERO)>0){
                    if (checkline==null){
                        break;
                    }
                    checkline.setLotattr05(palletizeData.getLotattr05());
                    checkline.setLotattr06(palletizeData.getLotattr06());
                    checkline.setLotattr07(palletizeData.getLotattr07());

                    checkline.setContainernumber(palletizeData.getContainnumber());
                    checkline.setTracenumber(palletizeData.getTracenumber());

                    qtyopen=checkline.getStorageqty();
                    if ((checkline.getPalqty()!=null) && (checkline.getPalqty().compareTo(BigDecimal.ZERO)>0)){
                        qtyopen=qtyopen.subtract(checkline.getPalqty());
                    }
                    //
                    if ((qtyopen==null) || (qtyopen.compareTo(BigDecimal.ZERO)<=0)){
                        index=index+1;
                        if (index>(matchlines.size()-1)){
                            break;
                        }
                        checkline=matchlines.get(index);
                        continue;
                    }
                    //
                    if (qtyopen.compareTo(total)>=0){
                        qtyopen=total;
                    }
                    details=this.createAsnLine(header, checkline, material, loc, qtyopen, checkline.getUdf07(), actionDto);
                    if (details==null){
                        m="创建入库单明细行失败.托盘码:"+palletize.getContainNumber();
                        return m;
                    }
                    this.asnDetailsService.save(details);
                    //3. 生成码盘数据
                    //palletize=this.createPalletizeData(palletizeData, material, actionDto);
                    palletize=this.createPalletizeData(palletizeData, header, details, material, qtyopen, checkline.getUdf07(), actionDto);
                    if (palletize!=null){
                        this.palletizeService.save(palletize);
                    }

                    //
                    total=total.subtract(qtyopen);
                    if ((total==null) || (total.compareTo(BigDecimal.ZERO)<=0)){
                        break;
                    }
                    //
                    index=index+1;
                    if (index>(matchlines.size()-1)){
                        break;
                    }
                    checkline=matchlines.get(index);
                    continue;
                }
            }
        }catch (Exception e){
            m="新增装箱异常.箱码:"+traceNumber+",托盘码:"+containNumber+",异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    public String calculateInventoyDataPalletizeQuantity(List<XwmsInventoryLineDto> lines, boolean onLotnumber){
        String m = "";
        if ((lines==null) || (lines.size()==0)){
            return m;
        }
        List<TwtActPalletizeList> pals=null;
        BigDecimal workqty=null;
        Map<String, Object> params=new HashedMap();
        Map<String, BigDecimal> groupSumm=new HashedMap();
        String gno="";
        BigDecimal total=null;
        try{
            //TODO:HU/202505
            pals=this.palletizeService.findAll(params, (Sort)null);
            if ((pals!=null) && (pals.size()>0)){
                for (TwtActPalletizeList p:pals){
                    if (p==null){
                        continue;
                    }
                    gno=InforWasExchangeSupport.groupKey(p);
                    if (onLotnumber){
                        gno=gno+"/"+StringUtils.ifNullOrBlank(p.getUdf07(),CodesConstants.COMMON_WILDCARD);
                    }
                    if (StringUtils.isNullOrBlank(gno)){
                       continue;
                    }
                    total=groupSumm.get(gno);
                    if (total==null){
                        total=BigDecimal.ZERO;
                    }
                    total=total.add(p.getQty());
                    groupSumm.put(gno, total);
                }
            }

            for (XwmsInventoryLineDto d:lines){
                if (d==null){
                    continue;
                }
                d.setPalqty(BigDecimal.ZERO);
                d.setPalqtyeach(d.getPalqty());

                if ((groupSumm!=null) && (groupSumm.size()>0)){
                    total=BigDecimal.ZERO;
                    gno=d.getGroupNumber();
                    if (!StringUtils.isNullOrBlank(gno)){
                        if (onLotnumber){
                            gno=gno.trim()+"/"+StringUtils.ifNullOrBlank(d.getUdf07(), CodesConstants.COMMON_WILDCARD);
                        }
                        total=groupSumm.get(gno);
                        if ((total!=null) && (total.compareTo(BigDecimal.ZERO)>0)){
                            d.setPalqty(total);
                            d.setPalqtyeach(d.getPalqty());
                        }
                    }
                }
                workqty=d.getStorageqty();
                if ((d.getPalqty()!=null) && (d.getPalqty().compareTo(BigDecimal.ZERO)>0)){
                    workqty=workqty.subtract(d.getPalqty());
                }
                d.setWorkqty(workqty);
                d.setWorkqtyeach(d.getWorkqty());
            }
        }catch (Exception e){
            m="计算码盘数量失败.错误:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    public String calculateInventoyRecordPalletizeQuantity(List<TwiInventoryXwmsDetails> lines, boolean onLotnumber){
        String m = "";
        if ((lines==null) || (lines.size()==0)){
            return m;
        }
        List<TwtActPalletizeList> pals=null;
        BigDecimal workqty=null;
        Map<String, Object> params=new HashedMap();
        Map<String, BigDecimal> groupSumm=new HashedMap();
        String gno="";
        BigDecimal total=null;
        try{
            //TODO:HU/202505
            pals=this.palletizeService.findAll(params, (Sort)null);
            if ((pals==null)||(pals.size()==0)){
                return m;
            }
            for (TwtActPalletizeList p:pals){
                if (p==null){
                    continue;
                }
                gno=InforWasExchangeSupport.groupKey(p);
                if (onLotnumber){
                    gno=gno+"/"+StringUtils.ifNullOrBlank(p.getUdf07(),CodesConstants.COMMON_WILDCARD);
                }
                if (StringUtils.isNullOrBlank(gno)){
                    continue;
                }
                total=groupSumm.get(gno);
                if (total==null){
                    total=BigDecimal.ZERO;
                }
                total=total.add(p.getQty());
                groupSumm.put(gno, total);
            }

            for (TwiInventoryXwmsDetails d:lines){
                if (d==null){
                    continue;
                }
                d.setPalQty(BigDecimal.ZERO);
                d.setPalQtyEach(d.getPalQty());
                total=BigDecimal.ZERO;
                gno=this.groupKey(d);
                if (!StringUtils.isNullOrBlank(gno)){
                    if (onLotnumber){
                        gno=gno.trim()+"/"+StringUtils.ifNullOrBlank(d.getUdf07(), CodesConstants.COMMON_WILDCARD);
                    }
                    total=groupSumm.get(gno);
                    if ((total!=null) && (total.compareTo(BigDecimal.ZERO)>0)){
                        d.setPalQty(total);
                        d.setPalQtyEach(d.getPalQty());
                    }
                }
                /**
                workqty=d.getStorageQty();
                if ((d.getPalQty()!=null) && (d.getPalQty().compareTo(BigDecimal.ZERO)>0)){
                    workqty=workqty.subtract(d.getPalQty());
                }
                d.setWorkqty(workqty);
                d.setWorkqtyeach(d.getWorkqty());
                **/
            }
        }catch (Exception e){
            m="计算码盘数量失败.错误:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }


    //用于ASN作业状态跟踪
    //deliveryLastStatus
    public String changeAsnDeliveryStatus(Long divisionid, Long docId, String containerNumber, BigDecimal weight, String statusCode, String worker){
        String m = "";
        if (StringUtils.isNullOrBlank(containerNumber)){
            return m;
        }
        if (docId==null){
            return m;
        }
        if (StringUtils.isNullOrBlank(statusCode)){
            return m;
        }
        if (divisionid==null){
            divisionid=XcmgAmConstants.CUSTOMER_ID_WWAREHOUSE_WH101;
        }
        if (StringUtils.isNullOrBlank(worker)){
            worker=SecurityUtils.getLoginUsername();
        }
        TwaDocAsnHeader header=null;
        try{
            header=this.asnService.findById(docId);
            if (header==null){
                return m;
            }
            if (header.getStatus().compareToIgnoreCase(WmsConstants.ASN_STATUS_PART_RECEIVE)>=0){
                return m;
            }
            if (!containerNumber.equalsIgnoreCase(header.getDeliveryContainerNum())){
                return m;
            }
            if ((header.getDeliveryLastStatus()!=null)
                    && (statusCode.compareToIgnoreCase(header.getDeliveryLastStatus())<=0)){
                return m;
            }
            if ((weight!=null) && (weight.compareTo(BigDecimal.ZERO)>0)){
                header.setHEdi09(weight);
            }
            header.setDeliveryLastStatus(statusCode);
            header.setLastModifiedBy(worker);
            header.setLastModifiedDate(new Date());
            this.asnService.save(header);
        }catch (Exception e){
            e.printStackTrace();
        }
        if ((statusCode.equalsIgnoreCase(WmsConstants.ASN_STATUS_CLOSE))
                || (statusCode.equalsIgnoreCase(WmsConstants.ASN_STATUS_CANCELL))){
            WorkDataHolders.get(divisionid).cleanPalletContainnumberOnAsn(containerNumber.trim());
        }
        return m;
    }

    public String changeAsnHeaderDeliveryStatus(Long documentId, String containerNumber, String statusCode, String worker){
        String m = "";
        if (StringUtils.isNullOrBlank(containerNumber)){
            return m;
        }
        if (StringUtils.isNullOrBlank(statusCode)){
            return m;
        }
        if (documentId==null){
            return m;
        }
        if (StringUtils.isNullOrBlank(worker)){
            worker=SecurityUtils.getLoginUsername();
        }
        TwaDocAsnHeader header=null;
        try{
            header=this.asnService.findById(documentId);
            if (header==null){
                return m;
            }
            if (header.getStatus().compareToIgnoreCase(WmsConstants.ASN_STATUS_RECEIVE)>0){
                return m;
            }
            if (!containerNumber.equalsIgnoreCase(header.getDeliveryContainerNum())){
                return m;
            }
            if ((header.getDeliveryLastStatus()!=null)
                    && (statusCode.compareToIgnoreCase(header.getDeliveryLastStatus())<=0)){
                return m;
            }
            header.setDeliveryLastStatus(statusCode);
            header.setLastModifiedBy(worker);
            header.setLastModifiedDate(new Date());
            this.asnService.save(header);
        }catch (Exception e){
            e.printStackTrace();
        }
        if ((statusCode.equalsIgnoreCase(WmsConstants.ASN_STATUS_CLOSE))
                || (statusCode.equalsIgnoreCase(WmsConstants.ASN_STATUS_CANCELL))){
            WorkDataHolders.get(header.getDivisionId()).cleanPalletContainnumberOnAsn(containerNumber.trim());
        }
        return m;
    }

    public List<XwmsInventoryLineDto> loadXwmsInventory(String warehousecCode, String materialCode, boolean grouping, TaskActionDto actionDto){
        List<XwmsInventoryLineDto> datas=new ArrayList<>();

        StorageQueryData params = null;
        List<StorageLineResultDto> lines=null;
        try{
            params = InforWasExchangeSupport.newQuery(InforWasXcmgExchangeConstants.INFOR_MAP_WH101_WAREHOUSER_ID, materialCode, "");
            if (grouping){
                lines=this.inforCommonWorkService.queryAndGroupInventory(params, actionDto);
            }else {
                lines=this.inforCommonWorkService.queryInventory(params, actionDto);
            }
            datas = this.inforCommonWorkService.translateTo(warehousecCode, lines);
        }catch (Exception e){
            e.printStackTrace();
        }
        return datas;
    }

    public List<XwmsInventoryLineDto> match(List<XwmsInventoryLineDto> allDatas, PalletizeChangeData palletizeData){
        List<XwmsInventoryLineDto> checkout=allDatas;
        if ((allDatas==null) || (allDatas.size()==0)){
            return  checkout;
        }
        if (palletizeData==null){
            return checkout;
        }
        checkout = new ArrayList<>();
        String gno=InforWasExchangeSupport.groupKey(palletizeData);
        for (XwmsInventoryLineDto xd:allDatas){
            if (xd==null){
                continue;
            }
            if (StringUtils.isNullOrBlank(xd.getGroupNumber())){
                continue;
            }
            if (xd.getGroupNumber().equalsIgnoreCase(gno)){
                checkout.add(xd);
            }
        }
        return checkout;
    }


/**==================================================================================================================**/
// ---- OUTBOUND/SO
/**==================================================================================================================**/

    public TwaDocSoHeader takeSoHeader(Long divisionId, List<TaskOrderDto> orderTasks, String dataSoureType, Map<String, TwmBasMaterial> materials, String worker){
        TwaDocSoHeader header=null;
        if ((orderTasks==null)||(orderTasks.size()==0)){
            return header;
        }
        if (divisionId==null){
            divisionId=XcmgAmConstants.DIVISION_WH101_ID;
        }
        //check
        TaskOrderDto orderline=null;
        String groupno="";
        List<TwaDocSoHeader> headers=null;
        TwmBasMaterial mat=null;
        try{
            orderline=orderTasks.get(0);
            groupno=InforWasExchangeSupport.groupKey(orderline);
            headers=this.dyncdataQueryService.xwmsSoHeaderOf(groupno);
            if ((headers!=null) && (headers.size()>0)){
                for (TwaDocSoHeader h:headers){
                    if (h==null){
                        continue;
                    }
                    if (h.getWaveId()!=null){
                        continue;
                    }
                    if (!WmsConstants.SO_STATUS_CREATE.equalsIgnoreCase(h.getStatus())){
                        continue;
                    }
                    header=h;
                    break;
                }
            }
            if (header!=null){
                return header;
            }
            //
            mat=null;
            if ((materials!=null) && (materials.size()>0)){
                mat=materials.get(orderline.getMCode());
            }
            if (mat==null){
                mat= this.materialService.lookup(StringUtils.ifNullOrBlank(orderline.getOwner(), XcmgAmConstants.CUSTOMER_CODE_XCMG_AM), orderline.getMCode().trim());
            }
            if (mat==null){
                return header;
            }
            header=new TwaDocSoHeader();
            header.setDocumentNumber(this.seqService.next(WmsConstants.SEQUENCE_NAME_DOC_SO));
            //header.setDocumentNumber(orderline.getErpCode().trim());
            header.setGlobalClientId(mat.getGlobalClientId());
            header.setCustomerId(mat.getCustomerId());
            header.setDivisionId(divisionId);
            header.setCategory(null);
            header.setType(WmsConstants.SO_TYPE_WORK_ORDER);
            header.setStatus(WmsConstants.SO_STATUS_CREATE);


            //分组唯一码
            header.setDeliveryTerms(groupno);

            //外购,自制,非生产,其它
            header.setCategory(dataSoureType);

            //外部单号
            header.setRefDocNumber(orderline.getSapCode());
            //工单号
            header.setRefAsnNumber(orderline.getOrderCode());
            //出库单号
            header.setRefSoNumber(orderline.getErpCode());
            //WBS
            header.setPaymentTerms(orderline.getOwbs());

            //分厂
            header.setConsigneeName(orderline.getFactory());
            //产线
            header.setPlanLoadPlace(orderline.getLineCode());
            //工位
            header.setPlanLoadDoor(orderline.getStation());
            //配盘点
            header.setDeliveryFromPlace(orderline.getStocktaking());

            //WBS
            header.setUdf03(orderline.getWbsno());
            //
            header.setHEdi03(orderline.getSapCode());      //外部单号
            header.setHEdi04(orderline.getOrderCode());    //订单号
            header.setHEdi05(orderline.getErpCode());       //出库单号
            header.setHEdi06(orderline.getFactory());       //分厂
            header.setHEdi07(orderline.getLineCode());      //产线
            header.setHEdi08(orderline.getStation());       //工位

            header.setCreateSource(InforWasXcmgExchangeConstants.SYS_XWMS);
            header.setDocPrior(WmsConstants.TASK_PRIOR_NORMAL);

            header.setEnabled(true);
            header.setEditable(true);
            header.setDelFlag(false);

            header.setCreatedDate(new Date());
            header.setCreatedBy(worker);
            header.setLastModifiedDate(header.getCreatedDate());
            header.setLastModifiedBy(header.getCreatedBy());
        }catch (Exception e){
            e.printStackTrace();
        }
        return header;
    }

    public TwaDocSoHeader takeSoHeader(Long divisionId, TaskOrderDto orderTask, String dataSoureType, Map<String, TwmBasMaterial> materials, String worker){
        TwaDocSoHeader header=null;
        if (orderTask==null){
            return header;
        }
        if (divisionId==null){
            divisionId=XcmgAmConstants.DIVISION_WH101_ID;
        }
        //check
        String groupno="";
        List<TwaDocSoHeader> headers=null;
        TwmBasMaterial mat=null;
        try{
            groupno=InforWasExchangeSupport.groupKey(orderTask);
            headers=this.dyncdataQueryService.xwmsSoHeaderOf(groupno);
            if ((headers!=null) && (headers.size()>0)){
                for (TwaDocSoHeader h:headers){
                    if (h==null){
                        continue;
                    }
                    if (h.getWaveId()!=null){
                        continue;
                    }
                    if (!WmsConstants.SO_STATUS_CREATE.equalsIgnoreCase(h.getStatus())){
                        continue;
                    }
                    header=h;
                    break;
                }
            }
            if (header!=null){
                return header;
            }
            //
            mat=null;
            if ((materials!=null) && (materials.size()>0)){
                mat=materials.get(orderTask.getMCode());
            }
            if (mat==null){
                mat= this.materialService.lookup(StringUtils.ifNullOrBlank(orderTask.getOwner(), XcmgAmConstants.CUSTOMER_CODE_XCMG_AM), orderTask.getMCode().trim());
                materials.put(orderTask.getMCode(), mat);
            }
            if (mat==null){
                return header;
            }
            header=new TwaDocSoHeader();
            header.setDocumentNumber(this.seqService.next(WmsConstants.SEQUENCE_NAME_DOC_SO));
            //header.setDocumentNumber(orderline.getErpCode().trim());
            header.setGlobalClientId(mat.getGlobalClientId());
            header.setCustomerId(mat.getCustomerId());
            header.setDivisionId(divisionId);
            header.setCategory(null);
            header.setType(WmsConstants.SO_TYPE_WORK_ORDER);
            header.setStatus(WmsConstants.SO_STATUS_CREATE);


            //分组唯一码
            header.setDeliveryTerms(groupno);

            //外购,自制,非生产,其它
            header.setCategory(dataSoureType);

            //外部单号
            header.setRefDocNumber(orderTask.getSapCode());
            //工单号
            header.setRefAsnNumber(orderTask.getOrderCode());
            //出库单号
            header.setRefSoNumber(orderTask.getErpCode());
            //WBS
            header.setPaymentTerms(orderTask.getOwbs());

            //分厂
            header.setConsigneeName(orderTask.getFactory());
            //产线
            header.setPlanLoadPlace(orderTask.getLineCode());
            //工位
            header.setPlanLoadDoor(orderTask.getStation());
            //配盘点
            header.setDeliveryFromPlace(orderTask.getStocktaking());

            //WBS
            header.setUdf03(orderTask.getWbsno());
            //
            header.setHEdi03(orderTask.getSapCode());      //外部单号
            header.setHEdi04(orderTask.getOrderCode());    //订单号
            header.setHEdi05(orderTask.getErpCode());       //出库单号
            header.setHEdi06(orderTask.getFactory());       //分厂
            header.setHEdi07(orderTask.getLineCode());      //产线
            header.setHEdi08(orderTask.getStation());       //工位

            header.setCreateSource(InforWasXcmgExchangeConstants.SYS_XWMS);
            header.setDocPrior(WmsConstants.TASK_PRIOR_NORMAL);

            header.setEnabled(true);
            header.setEditable(true);
            header.setDelFlag(false);

            header.setCreatedDate(new Date());
            header.setCreatedBy(worker);
            header.setLastModifiedDate(header.getCreatedDate());
            header.setLastModifiedBy(header.getCreatedBy());
        }catch (Exception e){
            e.printStackTrace();
        }
        return header;
    }

    public TwaDocSoHeader takeSoHeader(TwaInventoryDetails storage, String dataSoureType, String worker){
        TwaDocSoHeader header=null;
        if (storage==null){
            return header;
        }
        if (StringUtils.isNullOrBlank(dataSoureType)){
            dataSoureType=storage.getReserveCode();
        }
        if (StringUtils.isNullOrBlank(dataSoureType)){
            dataSoureType=XcmgAmConstants.WORK_SOURCE_PO;
        }
        //check
        String groupno="";
        List<TwaDocSoHeader> headers=null;
        TwmBasMaterial mat=null;
        try{
            //
            mat= this.materialService.lookup(storage.getMaterialId());
            if (mat==null){
                return header;
            }
            header=new TwaDocSoHeader();
            header.setDocumentNumber(this.seqService.next(WmsConstants.SEQUENCE_NAME_DOC_SO));
            header.setGlobalClientId(storage.getGlobalClientId());
            header.setCustomerId(storage.getCustomerId());
            header.setDivisionId(storage.getDivisionId());
            header.setCategory(null);
            header.setType(WmsConstants.SO_TYPE_WORK_ORDER);
            header.setStatus(WmsConstants.SO_STATUS_CREATE);


            //分组唯一码
            header.setDeliveryTerms(groupno);

            //外购,自制,非生产,其它
            header.setCategory(dataSoureType);

            //外部单号
            //header.setRefDocNumber(storage.getUdf03());
            header.setRefDocNumber(null);
            //工单号
            header.setRefAsnNumber(null);
            //出库单号
            header.setRefSoNumber(null);
            //WBS
            header.setPaymentTerms(null);

            //分厂
            header.setConsigneeName(null);
            //产线
            header.setPlanLoadPlace(null);             //storage.getUdf04());
            //工位
            header.setPlanLoadDoor(null);             //storage.getUdf05());
            //配盘点
            header.setDeliveryFromPlace(null);        //storage.getUdf06());

            //WBS
            header.setUdf03(null);
            //
            header.setHEdi03(null);      //storage.getUdf03()                 //外部单号
            header.setHEdi04(null);                                           //订单号
            header.setHEdi05(null);                                           //出库单号
            header.setHEdi06(null);                                           //分厂
            header.setHEdi07(null);      //storage.getUdf04());               //产线
            header.setHEdi08(null);      //storage.getUdf05());               //工位

            header.setCreateSource(CodesConstants.SYSTEM_WMS);
            header.setDocPrior(WmsConstants.TASK_PRIOR_NORMAL);

            header.setEnabled(true);
            header.setEditable(true);
            header.setDelFlag(false);

            header.setCreatedDate(new Date());
            header.setCreatedBy(worker);
            header.setLastModifiedDate(header.getCreatedDate());
            header.setLastModifiedBy(header.getCreatedBy());
        }catch (Exception e){
            e.printStackTrace();
        }
        return header;
    }

    public List<TwaDocSoDetails> createSoDetails(TwaDocSoHeader header, List<TaskOrderDto> orderTasks, Map<String, TwmBasMaterial> materials){
        //
        TwaDocSoDetails line=null;
        TwmBasMaterial material=null;
        String linenum=null;
        int index=0;
        List<TwaDocSoDetails> lines=new ArrayList<>();
        try{
            index = this.soDetailsService.maxLineNumber(header.getId());
            index=(int)(index/10);
            //
            for (TaskOrderDto t:orderTasks){
                if (t==null){
                    continue;
                }
                material=null;
                if ((materials!=null)&&(materials.size()>0)){
                    material=materials.get(t.getMCode());
                }
                if (material==null){
                    material=this.materialService.lookup(StringUtils.ifNullOrBlank(t.getOwner(), XcmgAmConstants.CUSTOMER_CODE_XCMG_AM), t.getMCode().trim());
                }
                if (material==null){
                    continue;
                }
                index++;
                line=new TwaDocSoDetails();
                line.setHeaderId(header.getId());
                /**
                 linenum=null;//lineData.getDoclinenumber();

                 if ((t.getRowNo()!=null) && (t.getRowNo()>0)){
                 linenum=String.valueOf(t.getRowNo());
                 }else {
                 //linenum=this.soDetailsService.nextLineNumber(header.getId());
                 //line.setLineNumber(String.format("%02d", (index*10)));
                 }
                 **/
                // linenum=this.soDetailsService.nextLineNumber(header.getId());
                //linenum = this.nextLineNumber(index); // String.format("%02d", (index*10));
                linenum =  StringUtils.lpad(String.valueOf(index*10), "0", 4L);
                line.setLineNumber(linenum.trim());

                line.setMaterialId(material.getId());
                line.setMaterialCode(material.getCode());
                line.setMaterialName(material.getName());
                if (!StringUtils.isNullOrBlank(t.getGoodName())){
                    line.setMaterialName(t.getGoodName());
                }
                line.setQtyOrdered(t.getQuantity());
                line.setQtyOrderedEach(line.getQtyOrdered());
                line.setQtyPalletizePal(BigDecimal.ZERO);
                line.setQtyPalletizeCase(BigDecimal.ZERO);
                line.setQtyPalletizeEach(BigDecimal.ZERO);
                line.setQtySoftallocated(BigDecimal.ZERO);
                line.setQtySoftallocatedEach(BigDecimal.ZERO);
                line.setQtyAllocated(BigDecimal.ZERO);
                line.setQtyAllocatedEach(BigDecimal.ZERO);
                line.setQtyPicked(BigDecimal.ZERO);
                line.setQtyPickedEach(line.getQtyPicked());
                line.setQtyChecked(t.getQuantity());
                line.setQtyCheckedEach(line.getQtyChecked());
                line.setQtyLoaded(BigDecimal.ZERO);
                line.setQtyLoadedEach(line.getQtyLoaded());
                line.setQtyShipped(BigDecimal.ZERO);
                line.setQtyShippedEach(line.getQtyShipped());
                line.setPackId(material.getPackId());
                line.setUomCode(CodesConstants.UOM_EACH);
                if (!StringUtils.isNullOrBlank(t.getUom())){
                    line.setUomCode(t.getUom());
                }
                line.setRefDocNumber(null);
                line.setRefLineNumber(null);
                line.setTotalPrice(null);
                line.setTotalCubic(null);
                line.setTotalGrossweight(null);
                line.setTotalNetweight(null);
                //
                line.setLineStatus(WmsConstants.SO_STATUS_CREATE);
                //
                line.setProductStatus(null);
                line.setProductStatusDescr(null);
                line.setRotationRuleId(null);
                line.setSoftallocRuleId(null);
                line.setAllocationRuleId(material.getAllocruleId());
                line.setAllocationMode(null);
                line.setAllocationType(XcmgAmConstants.SHIP_RULE_WAVE_LOTATTR_ALLOCATOR);
                line.setAllocationClass(null);
                line.setQuickAllocationFlag(CodesConstants.COMMON_FLAG_YES);
                line.setOverShippingFlag(CodesConstants.COMMON_FLAG_NO);
                line.setShortShippingFlag(CodesConstants.COMMON_FLAG_NO);
                //
                line.setCheckLotNumber(null);
                /**
                 if (!StringUtils.isNullOrBlank(to.getSupplier())) {
                 line.setCheckLotNumber(to.getSupplier().trim());
                 }
                 **/
                line.setCheckPickZoneId(null);
                line.setCheckLocgroupCode(null);
                line.setCheckPickLocId(null);
                line.setCheckContainNumber(null);
                line.setCheckTraceNumber(null);
                line.setCheckQualityStatus(null);
                line.setCheckFullStatus(null);
                line.setCheckReserveStatus(null);
                line.setCheckReserveNumber(null);
                line.setCheckTempClass(null);
                line.setCheckHumidityClass(null);
                line.setCheckWeightClass(null);
                line.setCheckStorageId(null);

                line.setMaterialMode(null);
                line.setPackMode(null);
                line.setQuantityMode(null);
                line.setSequenceMode(null);
                line.setBalanceMode(null);
                line.setCrossMode(null);
                line.setWaveMode(null);
                line.setDeliveryMode(null);

                line.setReplaceMaterialCode(null);
                line.setKitDocCode(null);
                line.setKitMaterialCode(null);
                line.setRefLineNumber(null);
                line.setSortationLocId(null);
                line.setPlantoLocId(null);
                line.setDockNumber(null);
                line.setReleaseStatus(CodesConstants.COMMON_RELEASE_STATUS_CREATED);
                line.setReserveStatus(null);
                line.setPickingStatus(null);
                line.setPackingStatus(null);
                line.setLoadingStatus(null);
                line.setShippingStatus(null);
                line.setFirstShipTime(null);
                line.setLastShipTime(null);

                //
                if (t.getRowNo()!=null){
                    line.setRefLineNumber(String.valueOf(t.getRowNo()));
                }
                //PO...（来源)
                if (!StringUtils.isNullOrBlank(header.getCategory())){
                    line.setCheckReserveStatus(header.getCategory().trim());
                }
                //WBS
                if (!StringUtils.isNullOrBlank(t.getWbsno())){
                    line.setCheckReserveNumber(t.getWbsno().trim());
                }
                line.setDeliveryMode(t.getTaskCode());

                //
                line.setLotattr01(null);
                line.setLotattr02(null);
                line.setLotattr03(null);
                line.setLotattr04(null);
                line.setLotattr05(null);
                line.setLotattr06(null);
                line.setLotattr07(null);
                line.setLotattr08(null);
                line.setLotattr09(null);
                line.setLotattr10(null);
                line.setLotattr11(null);
                line.setLotattr12(null);
                line.setLotattr13(null);
                line.setLotattr14(null);
                line.setLotattr15(null);
                line.setLotattr16(null);

                //批次号:WAS内部批次,先进先出
                line.setLotattr05(null);

                //供应商：允许通配供应商
                line.setLotattr06(null);
                if (!StringUtils.isNullOrBlank(t.getSupplier())){
                    line.setLotattr06(t.getSupplier().trim());
                }
                //WBS：严格匹配WBS
                line.setLotattr07(CodesConstants.COMMON_WILDCARD);
                if (!StringUtils.isNullOrBlank(t.getWbsno())){
                    line.setLotattr07(t.getWbsno().trim());
                }

                //
                line.setUdf01(null);
                line.setUdf02(null);
                line.setUdf03(null);
                line.setUdf04(null);
                line.setUdf05(null);
                line.setUdf06(null);
                line.setUdf07(null);
                line.setUdf08(null);
                line.setUdf09(null);
                line.setUdf10(null);

                line.setDEdi01(null);
                line.setDEdi02(null);
                line.setDEdi03(XcmgAmSupport.sameAsNull(t.getTaskCode()));
                line.setDEdi04(XcmgAmSupport.sameAsNull(t.getSupplier()));
                line.setDEdi05(XcmgAmSupport.sameAsNull(t.getWbsno()));
                line.setDEdi06(XcmgAmSupport.sameAsNull(t.getType()));
                line.setDEdi07(XcmgAmSupport.sameAsNull(t.getBatchNo()));
                line.setDEdi08(XcmgAmSupport.sameAsNull(t.getErpTime()));
                line.setDEdi09(null);
                line.setDEdi10(null);

                line.setDEdi11(XcmgAmSupport.sameAsNull(t.getFactory()));      //分厂
                line.setDEdi12(XcmgAmSupport.sameAsNull(t.getLineCode()));     //产线
                line.setDEdi13(XcmgAmSupport.sameAsNull(t.getStation()));      //工位
                line.setDEdi14(XcmgAmSupport.sameAsNull(t.getStocktaking()));  //配盘点
                line.setDEdi15(XcmgAmSupport.sameAsNull(t.getStkLocation()));  //库存地
                line.setDEdi16(XcmgAmSupport.sameAsNull(t.getFromLoc()));       //源库位
                line.setDEdi17(XcmgAmSupport.sameAsNull(t.getToLoc()));        //目标库位

                line.setDEdi18(null);
                line.setDEdi19(null);
                line.setDEdi20(null);
                line.setDelFlag(false);

                line.setCreatedDate(new Date());
                line.setCreatedBy(header.getCreatedBy());
                line.setLastModifiedDate(line.getCreatedDate());
                line.setLastModifiedBy(line.getCreatedBy());
                if (line!=null){
                    lines.add(line);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return lines;
    }

    //后期考虑批量创建(行号逻辑)
    public TwaDocSoDetails createSoDetails(TwaDocSoHeader header, TaskOrderDto orderTask, TwmBasMaterial material, int index){
        //
        TwaDocSoDetails line=null;
        if (header==null){
            return line;
        }
        if (orderTask==null){
            return line;
        }
        if (material==null){
            return line;
        }
        if (index<=0){
            index=1;
        }
        String linenum=null;
        try{
            line=new TwaDocSoDetails();
            line.setHeaderId(header.getId());
            /**
             linenum=null;//lineData.getDoclinenumber();

             if ((t.getRowNo()!=null) && (t.getRowNo()>0)){
             linenum=String.valueOf(t.getRowNo());
             }else {
             //linenum=this.soDetailsService.nextLineNumber(header.getId());
             //line.setLineNumber(String.format("%02d", (index*10)));
             }
             **/
            // linenum=this.soDetailsService.nextLineNumber(header.getId());
            //linenum = this.nextLineNumber(index); // String.format("%02d", (index*10));
            linenum =  StringUtils.lpad(String.valueOf(index*10), "0", 4L);
            line.setLineNumber(linenum.trim());

            line.setMaterialId(material.getId());
            line.setMaterialCode(material.getCode());
            line.setMaterialName(material.getName());
            if (!StringUtils.isNullOrBlank(orderTask.getGoodName())){
                line.setMaterialName(orderTask.getGoodName());
            }
            line.setQtyOrdered(orderTask.getQuantity());
            line.setQtyOrderedEach(line.getQtyOrdered());
            line.setQtyPalletizePal(BigDecimal.ZERO);
            line.setQtyPalletizeCase(BigDecimal.ZERO);
            line.setQtyPalletizeEach(BigDecimal.ZERO);
            line.setQtySoftallocated(BigDecimal.ZERO);
            line.setQtySoftallocatedEach(BigDecimal.ZERO);
            line.setQtyAllocated(BigDecimal.ZERO);
            line.setQtyAllocatedEach(BigDecimal.ZERO);
            line.setQtyPicked(BigDecimal.ZERO);
            line.setQtyPickedEach(line.getQtyPicked());
            line.setQtyChecked(orderTask.getQuantity());
            line.setQtyCheckedEach(line.getQtyChecked());
            line.setQtyLoaded(BigDecimal.ZERO);
            line.setQtyLoadedEach(line.getQtyLoaded());
            line.setQtyShipped(BigDecimal.ZERO);
            line.setQtyShippedEach(line.getQtyShipped());
            line.setPackId(material.getPackId());
            line.setUomCode(CodesConstants.UOM_EACH);
            if (!StringUtils.isNullOrBlank(orderTask.getUom())){
                line.setUomCode(orderTask.getUom());
            }
            line.setRefDocNumber(null);
            line.setRefLineNumber(null);
            line.setTotalPrice(null);
            line.setTotalCubic(null);
            line.setTotalGrossweight(null);
            line.setTotalNetweight(null);
            //
            line.setLineStatus(WmsConstants.SO_STATUS_CREATE);
            //
            line.setProductStatus(null);
            line.setProductStatusDescr(null);
            line.setRotationRuleId(null);
            line.setSoftallocRuleId(null);
            line.setAllocationRuleId(material.getAllocruleId());
            line.setAllocationMode(null);
            line.setAllocationType(XcmgAmConstants.SHIP_RULE_WAVE_LOTATTR_ALLOCATOR);
            line.setAllocationClass(null);
            line.setQuickAllocationFlag(CodesConstants.COMMON_FLAG_YES);
            line.setOverShippingFlag(CodesConstants.COMMON_FLAG_NO);
            line.setShortShippingFlag(CodesConstants.COMMON_FLAG_NO);
            //
            line.setCheckLotNumber(null);
            /**
             if (!StringUtils.isNullOrBlank(to.getSupplier())) {
             line.setCheckLotNumber(to.getSupplier().trim());
             }
             **/
            line.setCheckPickZoneId(null);
            line.setCheckLocgroupCode(null);
            line.setCheckPickLocId(null);
            line.setCheckContainNumber(null);
            line.setCheckTraceNumber(null);
            line.setCheckQualityStatus(null);
            line.setCheckFullStatus(null);
            line.setCheckReserveStatus(null);
            line.setCheckReserveNumber(null);
            line.setCheckTempClass(null);
            line.setCheckHumidityClass(null);
            line.setCheckWeightClass(null);
            line.setCheckStorageId(null);

            line.setMaterialMode(null);
            line.setPackMode(null);
            line.setQuantityMode(null);
            line.setSequenceMode(null);
            line.setBalanceMode(null);
            line.setCrossMode(null);
            line.setWaveMode(null);
            line.setDeliveryMode(null);

            line.setReplaceMaterialCode(null);
            line.setKitDocCode(null);
            line.setKitMaterialCode(null);
            line.setRefLineNumber(null);
            line.setSortationLocId(null);
            line.setPlantoLocId(null);
            line.setDockNumber(null);
            line.setReleaseStatus(CodesConstants.COMMON_RELEASE_STATUS_CREATED);
            line.setReserveStatus(null);
            line.setPickingStatus(null);
            line.setPackingStatus(null);
            line.setLoadingStatus(null);
            line.setShippingStatus(null);
            line.setFirstShipTime(null);
            line.setLastShipTime(null);

            //
            if (orderTask.getRowNo()!=null){
                line.setRefLineNumber(String.valueOf(orderTask.getRowNo()));
            }
            //PO...（来源)
            if (!StringUtils.isNullOrBlank(header.getCategory())){
                line.setCheckReserveStatus(header.getCategory().trim());
            }
            //WBS
            if (!StringUtils.isNullOrBlank(orderTask.getWbsno())){
                line.setCheckReserveNumber(orderTask.getWbsno().trim());
            }
            line.setDeliveryMode(orderTask.getTaskCode());

            //
            line.setLotattr01(null);
            line.setLotattr02(null);
            line.setLotattr03(null);
            line.setLotattr04(null);
            line.setLotattr05(null);
            line.setLotattr06(null);
            line.setLotattr07(null);
            line.setLotattr08(null);
            line.setLotattr09(null);
            line.setLotattr10(null);
            line.setLotattr11(null);
            line.setLotattr12(null);
            line.setLotattr13(null);
            line.setLotattr14(null);
            line.setLotattr15(null);
            line.setLotattr16(null);

            //批次号:WAS内部批次,先进先出
            line.setLotattr05(null);

            //供应商：允许通配供应商
            line.setLotattr06(null);
            if (!StringUtils.isNullOrBlank(orderTask.getSupplier())){
                line.setLotattr06(orderTask.getSupplier().trim());
            }
            //WBS：严格匹配WBS
            line.setLotattr07(CodesConstants.COMMON_WILDCARD);
            if (!StringUtils.isNullOrBlank(orderTask.getWbsno())){
                line.setLotattr07(orderTask.getWbsno().trim());
            }

            //
            line.setUdf01(null);
            line.setUdf02(null);
            line.setUdf03(null);
            line.setUdf04(null);
            line.setUdf05(null);
            line.setUdf06(null);
            line.setUdf07(null);
            line.setUdf08(null);
            line.setUdf09(null);
            line.setUdf10(null);

            line.setDEdi01(null);
            line.setDEdi02(null);
            line.setDEdi03(XcmgAmSupport.sameAsNull(orderTask.getTaskCode()));
            line.setDEdi04(XcmgAmSupport.sameAsNull(orderTask.getSupplier()));
            line.setDEdi05(XcmgAmSupport.sameAsNull(orderTask.getWbsno()));
            line.setDEdi06(XcmgAmSupport.sameAsNull(orderTask.getType()));
            line.setDEdi07(XcmgAmSupport.sameAsNull(orderTask.getBatchNo()));
            line.setDEdi08(XcmgAmSupport.sameAsNull(orderTask.getErpTime()));
            line.setDEdi09(null);
            line.setDEdi10(null);

            line.setDEdi11(XcmgAmSupport.sameAsNull(orderTask.getFactory()));      //分厂
            line.setDEdi12(XcmgAmSupport.sameAsNull(orderTask.getLineCode()));     //产线
            line.setDEdi13(XcmgAmSupport.sameAsNull(orderTask.getStation()));      //工位
            line.setDEdi14(XcmgAmSupport.sameAsNull(orderTask.getStocktaking()));  //配盘点
            line.setDEdi15(XcmgAmSupport.sameAsNull(orderTask.getStkLocation()));  //库存地
            line.setDEdi16(XcmgAmSupport.sameAsNull(orderTask.getFromLoc()));       //源库位
            line.setDEdi17(XcmgAmSupport.sameAsNull(orderTask.getToLoc()));        //目标库位

            line.setDEdi18(null);
            line.setDEdi19(null);
            line.setDEdi20(null);
            line.setDelFlag(false);

            line.setCreatedDate(new Date());
            line.setCreatedBy(header.getCreatedBy());
            line.setLastModifiedDate(line.getCreatedDate());
            line.setLastModifiedBy(line.getCreatedBy());
        }catch (Exception e){
            e.printStackTrace();
        }
        return line;
    }

    public TwaDocSoDetails createSoDetails(TwaDocSoHeader header, TwaInventoryDetails storage){
        //
        TwaDocSoDetails line=null;
        TwmBasMaterial material=null;
        String linenum=null;
        int index=0;
        List<TwaDocSoDetails> lines=new ArrayList<>();
        TwaDocAsnHeader aheader=null;
        TwaDocAsnDetails aline=null;
        try{
            index = this.soDetailsService.maxLineNumber(header.getId());
            index=(int)(index/10);

            material=this.materialService.lookup(storage.getMaterialId());
            if (material==null){
                return line;
            }
            index++;
            line=new TwaDocSoDetails();
            line.setHeaderId(header.getId());
            // linenum=this.soDetailsService.nextLineNumber(header.getId());
            //linenum = this.nextLineNumber(index); // String.format("%02d", (index*10));
            linenum =  StringUtils.lpad(String.valueOf(index*10), "0", 4L);
            line.setLineNumber(linenum.trim());

            line.setMaterialId(material.getId());
            line.setMaterialCode(material.getCode());
            line.setMaterialName(material.getName());
            line.setQtyOrdered(storage.getQty());
            line.setQtyOrderedEach(line.getQtyOrdered());
            line.setQtyPalletizePal(BigDecimal.ZERO);
            line.setQtyPalletizeCase(BigDecimal.ZERO);
            line.setQtyPalletizeEach(BigDecimal.ZERO);
            line.setQtySoftallocated(BigDecimal.ZERO);
            line.setQtySoftallocatedEach(BigDecimal.ZERO);
            line.setQtyAllocated(BigDecimal.ZERO);
            line.setQtyAllocatedEach(BigDecimal.ZERO);
            line.setQtyPicked(BigDecimal.ZERO);
            line.setQtyPickedEach(line.getQtyPicked());
            line.setQtyChecked(storage.getQty());
            line.setQtyCheckedEach(line.getQtyChecked());
            line.setQtyLoaded(BigDecimal.ZERO);
            line.setQtyLoadedEach(line.getQtyLoaded());
            line.setQtyShipped(BigDecimal.ZERO);
            line.setQtyShippedEach(line.getQtyShipped());
            line.setPackId(material.getPackId());
            line.setUomCode(CodesConstants.UOM_EACH);
            if (!StringUtils.isNullOrBlank(material.getShipUom())){
                line.setUomCode(material.getShipUom());
            }
            line.setRefDocNumber(null);
            line.setRefLineNumber(null);

            line.setTotalPrice(null);
            line.setTotalCubic(null);
            line.setTotalGrossweight(null);
            line.setTotalNetweight(null);
            //
            line.setLineStatus(WmsConstants.SO_STATUS_CREATE);
            //
            line.setProductStatus(null);
            line.setProductStatusDescr(null);
            line.setRotationRuleId(null);
            line.setSoftallocRuleId(null);
            line.setAllocationRuleId(material.getAllocruleId());
            line.setAllocationMode(null);
            line.setAllocationType(XcmgAmConstants.SHIP_RULE_WAVE_LOTATTR_ALLOCATOR);
            line.setAllocationClass(null);
            line.setQuickAllocationFlag(CodesConstants.COMMON_FLAG_YES);
            line.setOverShippingFlag(CodesConstants.COMMON_FLAG_NO);
            line.setShortShippingFlag(CodesConstants.COMMON_FLAG_NO);
            //
            line.setCheckLotNumber(storage.getLotNumber());
            line.setCheckPickZoneId(null);
            line.setCheckLocgroupCode(null);
            line.setCheckPickLocId(null);
            line.setCheckContainNumber(storage.getContainNumber());
            line.setCheckTraceNumber(storage.getTraceNumber());
            line.setCheckQualityStatus(null);
            line.setCheckFullStatus(null);
            line.setCheckReserveStatus(storage.getReserveCode());
            line.setCheckReserveNumber(null);
            line.setCheckTempClass(null);
            line.setCheckHumidityClass(null);
            line.setCheckWeightClass(null);
            line.setCheckStorageId(storage.getId());

            line.setMaterialMode(null);
            line.setPackMode(null);
            line.setQuantityMode(null);
            line.setSequenceMode(null);
            line.setBalanceMode(null);
            line.setCrossMode(null);
            line.setWaveMode(null);
            line.setDeliveryMode(null);

            line.setReplaceMaterialCode(null);
            line.setKitDocCode(null);
            line.setKitMaterialCode(null);
            line.setRefLineNumber(null);
            line.setSortationLocId(null);
            line.setPlantoLocId(null);
            line.setDockNumber(null);
            line.setReleaseStatus(CodesConstants.COMMON_RELEASE_STATUS_CREATED);
            line.setReserveStatus(null);
            line.setPickingStatus(null);
            line.setPackingStatus(null);
            line.setLoadingStatus(null);
            line.setShippingStatus(null);
            line.setFirstShipTime(null);
            line.setLastShipTime(null);

            //PO/KIT...（来源)
            if (!StringUtils.isNullOrBlank(header.getCategory())){
                line.setCheckReserveStatus(header.getCategory().trim());
            }
            //
            line.setCheckReserveNumber(null);
            line.setDeliveryMode(header.getDeliveryShipNum());

            //
            line.setLotattr01(null);
            line.setLotattr02(null);
            line.setLotattr03(null);
            line.setLotattr04(null);
            line.setLotattr05(storage.getLotNumber());
            line.setLotattr06(null);
            line.setLotattr07(null);
            line.setLotattr08(null);
            line.setLotattr09(null);
            line.setLotattr10(null);
            line.setLotattr11(null);
            line.setLotattr12(null);
            line.setLotattr13(null);
            line.setLotattr14(null);
            line.setLotattr15(null);
            line.setLotattr16(null);

            //供应商：无
            line.setLotattr06(null);
            //WBS：无
            line.setLotattr07(null);

            line.setKitDocCode(storage.getUdf03()); //配盘单号
            line.setRefDocNumber(line.getKitDocCode());



            //
            line.setUdf01(storage.getUdf01());
            line.setUdf02(storage.getUdf02());
            line.setUdf03(storage.getUdf03());
            line.setUdf04(storage.getUdf04());
            line.setUdf05(storage.getUdf05());
            line.setUdf06(storage.getUdf06());
            line.setUdf07(storage.getUdf07());
            line.setUdf08(storage.getUdf08());
            line.setUdf09(storage.getUdf09());
            line.setUdf10(storage.getUdf10());

            line.setDEdi01(null);
            line.setDEdi02(null);
            line.setDEdi03(null);
            line.setDEdi04(null);
            line.setDEdi05(null);
            line.setDEdi06(null);
            line.setDEdi07(storage.getUdf07());    //批次
            line.setDEdi08(null);
            line.setDEdi09(null);
            line.setDEdi10(null);

            line.setDEdi11(null);                   //分厂
            line.setDEdi12(storage.getUdf04());     //产线
            line.setDEdi13(storage.getUdf05());      //工位
            line.setDEdi14(storage.getUdf06());     //配盘点
            line.setDEdi15(null);  //库存地
            line.setDEdi16(null);       //源库位
            line.setDEdi16(null);        //目标库位

            if (storage.getRefDocDetailsId()!=null){
                aline=this.asnDetailsService.findById(storage.getRefDocDetailsId());
                if (aline!=null){
                    aheader=this.asnService.findById(aline.getHeaderId());
                }
                if ((aline!=null) && (aheader!=null)){
                    line.setDEdi05(aheader.getDocumentNumber());
                }
            }

            line.setDEdi17(null);
            line.setDEdi18(null);
            line.setDEdi19(null);
            line.setDEdi20(null);
            line.setDelFlag(false);

            line.setCreatedDate(new Date());
            line.setCreatedBy(header.getCreatedBy());
            line.setLastModifiedDate(line.getCreatedDate());
            line.setLastModifiedBy(line.getCreatedBy());
        }catch (Exception e){
            e.printStackTrace();
        }
        return line;
    }

    //后期考虑批量创建(行号逻辑)
    public TwaDocSoDetails createSoDetails(TwaDocSoHeader header, DeliveryNoteData deliveryNoteData, TwmBasMaterial material, int index){
        //
        TwaDocSoDetails line=null;
        if (header==null){
            return line;
        }
        if (deliveryNoteData==null){
            return line;
        }
        if (material==null){
            return line;
        }
        if (index<=0){
            index=1;
        }
        String linenum=null;
        try{
            line=new TwaDocSoDetails();
            line.setHeaderId(header.getId());
            if (index>0){
                linenum =  StringUtils.lpad(String.valueOf(index*10), "0", 4L);
            }
            if (!StringUtils.isNullOrBlank(deliveryNoteData.getZpszlhzpos())){
                linenum=deliveryNoteData.getZpszlhzpos().trim();
            }
            line.setLineNumber(linenum);

            this.populateSoDetails(line, deliveryNoteData, header, material);
            line.setCreatedDate(new Date());
            line.setCreatedBy(header.getCreatedBy());
            line.setLastModifiedDate(line.getCreatedDate());
            line.setLastModifiedBy(line.getCreatedBy());
        }catch (Exception e){
            e.printStackTrace();
        }
        return line;
    }

    private String populateSoDetails(TwaDocSoDetails line, DeliveryNoteData deliveryNoteData, TwaDocSoHeader header, TwmBasMaterial material){
        String m = "";
        if (line==null){
            return m;
        }
        if (deliveryNoteData==null){
            return m;
        }
        if (material==null){
            return m;
        }
        line.setMaterialId(material.getId());
        line.setMaterialCode(material.getCode());
        line.setMaterialName(material.getName());
        if (!StringUtils.isNullOrBlank(deliveryNoteData.getMaktx())){
            line.setMaterialName(deliveryNoteData.getMaktx().trim());
        }
        line.setQtyOrdered(deliveryNoteData.getZpssl());
        line.setQtyOrderedEach(line.getQtyOrdered());
        line.setQtyPalletizePal(BigDecimal.ZERO);
        line.setQtyPalletizeCase(BigDecimal.ZERO);
        line.setQtyPalletizeEach(BigDecimal.ZERO);
        line.setQtySoftallocated(BigDecimal.ZERO);
        line.setQtySoftallocatedEach(BigDecimal.ZERO);
        line.setQtyAllocated(BigDecimal.ZERO);
        line.setQtyAllocatedEach(BigDecimal.ZERO);
        line.setQtyPicked(BigDecimal.ZERO);
        line.setQtyPickedEach(line.getQtyPicked());
        line.setQtyChecked(deliveryNoteData.getZpssl());
        line.setQtyCheckedEach(line.getQtyChecked());
        line.setQtyLoaded(BigDecimal.ZERO);
        line.setQtyLoadedEach(line.getQtyLoaded());
        line.setQtyShipped(BigDecimal.ZERO);
        line.setQtyShippedEach(line.getQtyShipped());
        line.setPackId(material.getPackId());
        line.setUomCode(CodesConstants.UOM_EACH);
        line.setRefDocNumber(null);
        line.setRefLineNumber(null);
        line.setTotalPrice(null);
        line.setTotalCubic(null);
        line.setTotalGrossweight(null);
        line.setTotalNetweight(null);
        //
        line.setLineStatus(WmsConstants.SO_STATUS_CREATE);
        //
        line.setProductStatus(null);
        line.setProductStatusDescr(null);
        line.setRotationRuleId(null);
        line.setSoftallocRuleId(null);
        line.setAllocationRuleId(material.getAllocruleId());
        line.setAllocationMode(null);
        line.setAllocationType(XcmgAmConstants.SHIP_RULE_WAVE_LOTATTR_ALLOCATOR);
        line.setAllocationClass(null);
        line.setQuickAllocationFlag(CodesConstants.COMMON_FLAG_YES);
        line.setOverShippingFlag(CodesConstants.COMMON_FLAG_NO);
        line.setShortShippingFlag(CodesConstants.COMMON_FLAG_NO);
        //
        line.setCheckLotNumber(null);
        /**
         if (!StringUtils.isNullOrBlank(to.getSupplier())) {
         line.setCheckLotNumber(to.getSupplier().trim());
         }
         **/
        line.setCheckPickZoneId(null);
        line.setCheckLocgroupCode(null);
        line.setCheckPickLocId(null);
        line.setCheckContainNumber(null);
        line.setCheckTraceNumber(null);
        line.setCheckQualityStatus(null);
        line.setCheckFullStatus(null);
        line.setCheckReserveStatus(null);
        line.setCheckReserveNumber(null);
        line.setCheckTempClass(null);
        line.setCheckHumidityClass(null);
        line.setCheckWeightClass(null);
        line.setCheckStorageId(null);

        line.setMaterialMode(null);
        line.setPackMode(null);
        line.setQuantityMode(null);
        line.setSequenceMode(null);
        line.setBalanceMode(null);
        line.setCrossMode(null);
        line.setWaveMode(null);
        line.setDeliveryMode(null);

        line.setReplaceMaterialCode(null);
        line.setKitDocCode(null);
        line.setKitMaterialCode(null);
        line.setRefLineNumber(null);
        line.setSortationLocId(null);
        line.setPlantoLocId(null);
        line.setDockNumber(null);
        line.setReleaseStatus(CodesConstants.COMMON_RELEASE_STATUS_CREATED);
        line.setReserveStatus(null);
        line.setPickingStatus(null);
        line.setPackingStatus(null);
        line.setLoadingStatus(null);
        line.setShippingStatus(null);
        line.setFirstShipTime(null);
        line.setLastShipTime(null);

        //
        if (deliveryNoteData.getZpszlpos()!=null){
            line.setRefLineNumber(String.valueOf(deliveryNoteData.getZpszlpos()));
        }
        //PO...（来源)
        if (!StringUtils.isNullOrBlank(header.getCategory())){
            line.setCheckReserveStatus(header.getCategory().trim());
        }
        //WBS
        if (!StringUtils.isNullOrBlank(deliveryNoteData.getProjn())){
            line.setCheckReserveNumber(deliveryNoteData.getProjn().trim());
        }
        line.setDeliveryMode(deliveryNoteData.getZpszlnum());

        //
        line.setLotattr01(null);
        line.setLotattr02(null);
        line.setLotattr03(null);
        line.setLotattr04(null);
        line.setLotattr05(null);
        line.setLotattr06(null);
        line.setLotattr07(null);
        line.setLotattr08(null);
        line.setLotattr09(null);
        line.setLotattr10(null);
        line.setLotattr11(null);
        line.setLotattr12(null);
        line.setLotattr13(null);
        line.setLotattr14(null);
        line.setLotattr15(null);
        line.setLotattr16(null);

        //批次号:WAS内部批次,先进先出
        line.setLotattr05(null);

        //供应商：允许通配供应商
        line.setLotattr06(SapWasXcmgExchangeConstants.SELF_MADE_SUPPLIER_CODE);
        //WBS：严格匹配WBS
        line.setLotattr07(CodesConstants.COMMON_WILDCARD);
        if (!StringUtils.isNullOrBlank(deliveryNoteData.getProjn())){
            line.setLotattr07(deliveryNoteData.getProjn().trim());
        }

        //
        line.setUdf01(null);
        line.setUdf02(null);
        line.setUdf03(null);
        line.setUdf04(null);
        line.setUdf05(null);
        line.setUdf06(null);
        line.setUdf07(null);
        line.setUdf08(null);
        line.setUdf09(null);
        line.setUdf10(null);

        line.setDEdi01(null);
        line.setDEdi02(null);
        line.setDEdi03(XcmgAmSupport.sameAsNull(deliveryNoteData.getZpszlnum())); //
        line.setDEdi04(null);
        line.setDEdi05(XcmgAmSupport.sameAsNull(deliveryNoteData.getProjn()));
        line.setDEdi06(null);
        line.setDEdi07(null);
        line.setDEdi08(null);
        line.setDEdi09(null);
        line.setDEdi10(null);
        /**
         line.setDEdi11(null);      //分厂
         line.setDEdi12(null);     //产线
         line.setDEdi13(null);      //工位
         line.setDEdi14(null);  //配盘点
         line.setDEdi15(null);  //库存地
         line.setDEdi16(null);       //源库位
         line.setDEdi17(null);        //目标库位
         line.setDEdi18(null);
         line.setDEdi19(null);
         line.setDEdi20(null);
         **/

        line.setDEdi08(deliveryNoteData.getZpszlnum());
        line.setDEdi09(deliveryNoteData.getZypssl());
        line.setDEdi10(null);
        line.setDEdi11(deliveryNoteData.getErdat());      //分厂
        line.setDEdi12(deliveryNoteData.getZpsrq());     //产线
        line.setDEdi13(deliveryNoteData.getLgort04());      //工位
        line.setDEdi14(null);  //配盘点
        line.setDEdi15(null);  //库存地
        line.setDEdi16(null);       //源库位
        line.setDEdi17(null);        //目标库位
        line.setDEdi18(null);
        line.setDEdi19(null);
        line.setDEdi20(null);
        line.setDelFlag(false);
        /**
         ZPSZLNUM	配送指令号	ZPSZLNUM
         ZPSZLHZPOS	配送指令汇总项目	ZPSZLPOSHZ
         MATNR	物料编号	MATNR
         MAKTX	物料描述	MAKTX
         ZPSSL	配送数量	ZPSSL
         ERDAT	记录创建日期	ERDAT
         ZPSRQ	配送日期	ZPSRQ
         LGORT_RESB	存储地点	LGORT_D
         ZYPSSL	已配送数量	ZYPSSL
         ERNAM	创建对象的人员名称	ERNAM
         ZPSZLPOS	配送指令项目	ZPSZLPOS
         AUFNR	订单编号	AUFNR
         PROJN	订单wbs
         DISPO	订单MRP控制者
         LGORT04	内配发出库地点	ZLGORT04
         ZPSLX	配送类型	ZPSLX
         PSPEL	WBS 要素	PS_POSNR
         ZZTSC	删除	ZZTSC
         ZZTGB	关闭	ZZTGB
         ZPSQYMS	配送区域描述	ZPSQYMS
         RSNUM	预留/相关需求的编号	RSNUM
         RSPOS	预留 / 相关需求的项目编号	RSPOS
         LTXA1	工序短文本	LTXA1
         ARBPL	工作中心	ARBPL
         AENAM	更改人
         **/
        return m;
    }

/**==================================================================================================================**/
// ---- OUTBOUND/WAVE
/**==================================================================================================================**/
    //加入到波次
    //newWave:新创建波次
    public String addToWave(Long[] docIds, boolean newWave, DocumentActionDto actionDto) {
        String m = "";

        boolean failed=false;
        TwaDocWaveHeader wave=null;
        Long docid=null;
        TwaDocSoHeader so=null;
        String soinfo=null;
        boolean changed=false;
        try {
            for (Long did : docIds) {
                if (did == null) {
                    continue;
                }
                docid = did;
                if (docid == null) {
                    return m;
                }

                so = this.soService.findById(docid);
                if (so == null) {
                    m = "创建波次失败,找不到订单:" + String.valueOf(docid);
                    return m;
                }
                if ((WmsConstants.SO_STATUS_CLOSE.equalsIgnoreCase(so.getStatus()))
                        || ((WmsConstants.SO_STATUS_CANCELL.equalsIgnoreCase(so.getStatus())))){
                    m = "创建波次失败,订单已经关闭/取消.单号:" + so.getDocumentNumber();
                    return m;
                }
                if (CodesConstants.COMMON_FLAG_YES.equalsIgnoreCase(this.waveCreateStrictMode)){
                    if (so.getWaveId()!=null){
                        m = "订单已经加入波次。如需要重新创建波次，请先取消已创建波次.单号:" + so.getDocumentNumber();
                        return m;
                    }
                }

                if (actionDto == null) {
                    actionDto = new DocumentActionDto();
                }
                actionDto.setCheckGlobalClientId(so.getGlobalClientId());
                actionDto.setCheckCustomerId(so.getCustomerId());
                actionDto.setCheckDivisionId(so.getDivisionId());
                actionDto.setBatchNumber(TextUtils.genBatchNumber());

                if (newWave) {
                    wave = this.waveService.createWave(so, actionDto);
                }
                if (wave == null) {
                    wave = this.waveService.createWave(so, actionDto);
                    if (wave == null) {
                        m = "创建波次失败";
                        return m;
                    }
                }
                //订单WBS
                /**
                soinfo=wave.getSortationMode();
                if (StringUtils.isNullOrBlank(soinfo)){
                    soinfo=so.getPaymentTerms();
                    wave.setSortationLocationCode(soinfo);
                    changed=true;
                }
                 **/
                //订单WBS
                soinfo=wave.getSortationLocationCode();
                if ((!StringUtils.isNullOrBlank(so.getPaymentTerms()))
                        && ((soinfo==null) ||(soinfo.indexOf(so.getPaymentTerms())<0))){
                    soinfo=StringUtils.ifNullOrBlank(soinfo,"");
                    if (!StringUtils.isNullOrBlank(soinfo)){
                        soinfo=soinfo+",";
                    }
                    soinfo=soinfo+so.getPaymentTerms();
                    wave.setSortationLocationCode(soinfo);
                    changed=true;
                }

                //工位
                soinfo=wave.getNotes();
                if ((!StringUtils.isNullOrBlank(so.getPlanLoadDoor()))
                        &&((soinfo==null) ||(soinfo.indexOf(so.getPlanLoadDoor())<0))){
                    soinfo=StringUtils.ifNullOrBlank(soinfo,"");
                    if (!StringUtils.isNullOrBlank(soinfo)){
                        soinfo=soinfo+",";
                    }
                    soinfo=soinfo+so.getPlanLoadDoor();
                    wave.setNotes(soinfo);
                    changed=true;
                }
                if (changed){
                    this.waveService.save(wave);
                }
                //

                m = this.waveService.addSo(wave, Arrays.asList(docid), actionDto);
                if (!StringUtils.isNullOrBlank(m)) {
                    return m;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            m="创建波次失败:"+e.getMessage();
        }
        return m;
    }

    public String promptWave(Long waveId, String worker){
        String m = "";
        if (waveId==null){
            return m;
        }
        if (StringUtils.isNullOrBlank(worker)){
            worker=SecurityUtils.getLoginUsername();
        }
        TwaDocWaveHeader wave=null;
        try{
            wave=this.waveService.findById(waveId);
            if (wave==null){
                m="找不到波次,请确认是否已删除.Id:"+String.valueOf(waveId);
                return m;
            }
            //
            wave.setDocPrior(XcmgAmConstants.PRIOR_HIGH);
            wave.setLastModifiedBy(worker);
            wave.setLastModifiedDate(new Date());
            this.waveService.save(wave);
        }catch (Exception e){
            m="提升波次优先级失败.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    public String setPickStation(Long waveId, List<String> pickStations, String worker){
        String m = "";
        if (waveId==null){
            return m;
        }

        if ((pickStations==null) || (pickStations.size()==0)){
            m="波次必须指定拣货站台.";
            return m;
        }

        if (StringUtils.isNullOrBlank(worker)){
            worker=SecurityUtils.getLoginUsername();
        }
        TwaDocWaveHeader wave=null;
        String mstation="";
        String pointcodes="";
        LocationLineDto loc=null;
        try{
            wave=this.waveService.findById(waveId);
            if (wave==null){
                m="找不到波次,请确认是否已删除.Id:"+String.valueOf(waveId);
                return m;
            }
            if (WmsConstants.SO_STATUS_ALLOCATE.compareTo(wave.getStatus())<=0){
                m="波次已经开始作业,不能再次指定拣货站台.波次号:"+wave.getDocumentNumber();
                return m;
            }
            if (WmsConstants.SO_STATUS_SHIP.compareTo(wave.getStatus())<=0){
                m="波次已经开始发货,不能再次指定拣货站台.波次号:"+wave.getDocumentNumber();
                return m;
            }
            for (String d:pickStations){
                if (StringUtils.isNullOrBlank(d)){
                    continue;
                }
                loc=this.locationResolver.lookup(wave.getDivisionId(), d.trim());
                if (loc==null){
                    m="找不到拣货站台,请确认是否误删除.站台号:"+d;
                    return m;
                }
                if (StringUtils.isNullOrBlank(mstation)){
                    mstation=loc.getLocationCode();
                }
                if (!StringUtils.isNullOrBlank(pointcodes)){
                    pointcodes=pointcodes+";";
                }
                pointcodes=pointcodes+this.wcsCustomWorkService.takePointcode(loc);
            }
            if (StringUtils.isNullOrBlank(mstation)){
                m="未找到有效的拣货站台.";
                return m;
            }
            //
            wave.setDockNumber(mstation);
            wave.setPickLocationCode(mstation);
            wave.setWorkHandleCode(pointcodes);
            wave.setLastModifiedBy(worker);
            wave.setLastModifiedDate(new Date());
            this.waveService.save(wave);
        }catch (Exception e){
            m="设置波次拣货站台失败.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    public String executeWave(Long waveId, String worker){
        String m="";
        //
        TwaDocWaveHeader header=null;
        List<TwtActTaskList> tasks=null;
        String batchnum="";
        List<TwtActAllocationList> allocations=null;
        try{
            header = this.waveService.findById(waveId);
            if (header == null) {
                m = "找不到波次数据,请确认是否已删除.ID:" + String.valueOf(waveId);
                return m;
            }
            if (WmsConstants.SO_STATUS_CLOSE.equalsIgnoreCase(header.getStatus())) {
                m = "波次单已经关闭,无法执行.单号:" + header.getDocumentNumber();
                return m;
            }
            if (WmsConstants.SO_STATUS_CANCELL.equalsIgnoreCase(header.getStatus())) {
                m = "波次已经取消,无法执行.单号:" + header.getDocumentNumber();
                return m;
            }
            if (StringUtils.isNullOrBlank(header.getPickLocationCode())){
                m = "尚未指定波次拣货站台,无法执行.单号:" + header.getDocumentNumber();
                return m;
            }
            /**
             if (WmsConstants.SO_STATUS_ALLOCATE.equalsIgnoreCase(header.getStatus())) {
             m = "波次尚未分配,无法执行.单号:" + header.getDocumentNumber();
             return m;
             }
             **/
            allocations=new ArrayList<>();
            if (!WmsConstants.SO_STATUS_ALLOCATE.equalsIgnoreCase(header.getStatus())){
                m = this.allocate(header, batchnum, worker, allocations);
                if (!StringUtils.isNullOrBlank(m)){
                    return m;
                }
            }
            if ((allocations==null) || (allocations.size()==0)){
                m = "没有生成分配数据,请确认是否已分配,或库存不匹配.单号:" + header.getDocumentNumber();
                return m;
            }
            tasks=this.taskService.queryWorkingWaveTasks(waveId);
            if ((tasks==null) || (tasks.size()==0)){
                return m;
            }
            m = this.sendWasTaskToWcs(tasks, batchnum, worker);
        }catch (Exception e){
            m="波次执行出库出错.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }


/**==================================================================================================================**/
// ---- OUTBOUND/SHIP
/**==================================================================================================================**/
    //暂时停用
    //XWMS接口
    public String shipmentByContainerNumber(String containerNumber, String worker){
        String m = "";
        if (StringUtils.isNullOrBlank(containerNumber)){
            m="请指定发货托盘";
            return m;
        }
        if (StringUtils.isNullOrBlank(worker)){
            worker=SecurityUtils.getLoginUsername();
        }
        containerNumber=containerNumber.trim();
        List<TwtActTaskList> tasks=null;
        try{
            tasks=this.taskService.queryWorkingTasks(WmsConstants.TASK_TYPE_PICK, containerNumber);
            if ((tasks==null)||(tasks.size()==0)){
                m="找不到拣货任务,请确认是否已经发货.托盘码:"+containerNumber;
                return m;
            }
            m=this.shipmentByTasks(tasks, containerNumber, worker);
        }catch (Exception e){
            m="执行发货失败.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    public String shipmentByAllocationId(Long allocationId, String containerNumber, String worker){
        String m = "";
        if (allocationId==null){
            m="请指定发货记录";
            return m;
        }
        TwtActAllocationList allocation=null;
        List<TwaInventoryDetails> storages=null;
        LocationLineDto loc=null;
        String czonecode="";
        String pzonecode="";
        try{
            allocation=this.allocationService.findById(allocationId);
            if (allocation==null){
                m="找不到拣货记录，请确认是否已经删除.ID:"+String.valueOf(allocationId);
                return m;
            }
            if (StringUtils.isNullOrBlank(containerNumber)){
                containerNumber=allocation.getFromContainNumber();
            }
            storages=this.inventoryService.findByContainNumber(containerNumber);
            if ((storages==null)||(storages.size()==0)){
               m="找不到托盘库存，请确认是否已经拣货.托盘码:"+containerNumber;
               return m;
            }
            loc=this.locationResolver.lookup(storages.get(0).getLocId());
            if (WmsConstants.LOCATION_TYPE_BIN.equalsIgnoreCase(loc.getLocationType())){
               m="系统显示托盘在库内，请确认设备作业状态.托盘码:"+containerNumber;
               return m;
            }
            if (this.livePickMode()){
                czonecode=this.currentZone(containerNumber);
                if (XcmgAmConstants.onlinePickZoneMap.containsKey(czonecode)){
                    pzonecode=this.locationZone(allocation.getToLocId());
                    if (!czonecode.equalsIgnoreCase(pzonecode)){
                        m="非当前库区拣货任务,不能执行拣货.请确认库存当前库位.托盘码:"+containerNumber;
                        return m;
                    }
                }
            }
            m = this.shipmentByAllocation(allocation, containerNumber, worker);
        }catch (Exception e){
            m="确认发货失败.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    public String shipmentByAllocation(TwtActAllocationList allocation, String containerNumber, String worker){
        String m = "";
        if (allocation==null){
            m="请指定发货记录";
            return m;
        }
        if (StringUtils.isNullOrBlank(containerNumber)){
            m="请指定发货托盘";
            return m;
        }
        if (this.closed(allocation)){
            m="已经发货,不能重复确认.托盘码:"+containerNumber;
            return m;
        }
        if (StringUtils.isNullOrBlank(worker)){
            worker=SecurityUtils.getLoginUsername();
        }
        containerNumber=containerNumber.trim();
        //
        String mline=null;
        List<TwtActTaskList> tasks=null;
        List<TwtActTransList> trans=null;
        FuncReplyData<TaskReportResultDto> reportResults=null;
        try{
            if (!containerNumber.equalsIgnoreCase(allocation.getFromContainNumber())){
                m="确认发货失败,数据不一致.确认托盘码:"+containerNumber+"拣货托盘码:"+allocation.getFromContainNumber();
                return m;
            }
            tasks=this.taskService.refPickTask(allocation.getId());
            if ((tasks==null)||(tasks.size()==0)){
                m="找不到拣货任务,请确认是否已经发货.托盘码:"+containerNumber;
                return m;
            }
            m=this.shipmentByTasks(tasks, containerNumber, worker);
            if (!StringUtils.isNullOrBlank(m)){
                return m;
            }
            trans=this.dyncdataQueryService.queryTransByAllocation(allocation.getId());
            if ((trans==null)||(trans.size()==0)){
                m="发生异常,未生成发货交易.分配ID:"+String.valueOf(allocation.getId());
                return m;
            }
            for (TwtActTransList t:trans){
                if (t==null){
                    continue;
                }
                if (!containerNumber.equalsIgnoreCase(t.getFromContainNumber())){
                    m="确认发货失败,数据不一致.确认托盘码:"+containerNumber+"发货托盘码:"+allocation.getFromContainNumber();
                    return m;
                }
                if ((allocation.getWaveDetailsId()==null)
                            || (!allocation.getWaveDetailsId().equals(t.getWaveDetailsId()))){
                    m="确认发货失败,数据不一致.确认波次:"+String.valueOf(allocation.getWaveDetailsId())+",发货波次:"+String.valueOf(t.getWaveDetailsId());
                    return m;
                }
                reportResults = this.handleWasTransDataToXwms(t, false, worker);
                mline=InforWasExchangeSupport.errorMessage(reportResults);
                if (StringUtils.isNullOrBlank(mline)){
                    m=m+mline+"\n\r";
                }
            }
        }catch (Exception e){
            m="执行发货失败.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    public String saveShiplostInfo(Long allocationId, String lostInfo, String worker){
        String m = "";
        return m;
    }

    private String saveEdiSendChange(TwtActTransList trans, FuncReplyData<TaskReportResultDto> result, boolean repost, String worker){
        String m="";
        if (result==null){
            return m;
        }
        if (trans==null){
            return m;
        }
        List<TwiActTransList> etrans=null;
        String errortext="";
        try{
            errortext=InforWasExchangeSupport.errorMessage(result);

            if (StringUtils.isNullOrBlank(errortext)){
                if ((result.getResultData()!=null) && (result.getResultData().getProcessOutputs()!=null)){
                    if (!InforWasXcmgExchangeConstants.RESULT_CODE_OK.equalsIgnoreCase(result.getResultData().getProcessOutputs().getResultcode())){
                        errortext=StringUtils.ifNullOrBlank(result.getResultData().getProcessOutputs().getResultcode(),"");
                        if (!StringUtils.isNullOrBlank(result.getResultData().getProcessOutputs().getMessage())){
                            errortext=errortext+"//"+result.getResultData().getProcessOutputs().getMessage();
                        }
                    }
                }
            }
            if (errortext.length()>700){
                errortext=errortext.substring(0, 700);
            }
            if (!repost){
                m = this.createEdiTrans(trans, errortext, worker);
            }else{
                etrans=this.dyncdataQueryService.queryEdiTransByTransId(trans.getId());
                if ((etrans!=null) && (etrans.size()>0)){
                    m = this.updateEdiTransData(etrans.get(0), worker,  "", errortext);
                }
            }
            this.updateEdiTransData(trans, worker, errortext);
            this.transService.save(trans);
        }catch (Exception e){
            e.printStackTrace();
        }
        return m;
    }

    private String saveEdiSendChange(TwiActTransList trans, FuncReplyData<TaskReportResultDto> result, boolean repost, String notes, String worker){
        String m="";
        if (result==null){
            return m;
        }
        if (trans==null){
            return m;
        }
        List<TwiActTransList> etrans=null;
        String errortext="";
        try{
            errortext=InforWasExchangeSupport.errorMessage(result);
            if (errortext.length()>700){
                errortext=errortext.substring(0, 700);
            }
            if (StringUtils.isNullOrBlank(errortext)){
                if ((result.getResultData()!=null) && (result.getResultData().getProcessOutputs()!=null)
                        && (!StringUtils.isNullOrBlank(result.getResultData().getProcessOutputs().getResultcode()))){
                    if (!InforWasXcmgExchangeConstants.RESULT_CODE_OK.equalsIgnoreCase(result.getResultData().getProcessOutputs().getResultcode())){
                        if (!StringUtils.isNullOrBlank(result.getResultData().getProcessOutputs().getMessage())){
                            errortext=result.getResultData().getProcessOutputs().getResultcode()+"/"+result.getResultData().getProcessOutputs().getMessage();
                        }else {
                            errortext=result.getResultData().getProcessOutputs().getResultcode()+"/异常";
                        }
                    }
                }
            }
            if (StringUtils.isNullOrBlank(errortext)){
                this.updateEdiTransData(trans, worker, CodesConstants.COMMON_STATUS_CLOSED,  errortext);
            }else{
                this.updateEdiTransData(trans, worker, CodesConstants.COMMON_STATUS_APP_ERROR, errortext);
            }
            if (!StringUtils.isNullOrBlank(notes)) {
                trans.setNotes(notes.trim());
            }
            this.ediTransactionService.save(trans);
        }catch (Exception e){
            e.printStackTrace();
        }
        return m;
    }

    private String saveEdiSendChange(Map<String, TwtActTransList> map, FuncReplyData<TaskReportResultDto> result, boolean repost, String worker){
        String m="";
        if (result==null){
            return m;
        }

        TwtActTransList tran=null;
        List<TwiActTransList> etrans=null;
        String errortext="";
        try{
            if (map!=null){
                if (map.size()==1){
                    tran=map.values().iterator().next();
                }else {
                    if (result.getResultData()==null){
                        return m;
                    }
                    if (result.getResultData().getProcessOutputs()==null){
                        return m;
                    }
                    if (result.getResultData().getProcessOutputs().getTaskkey()==null){
                        return m;
                    }
                    tran=map.get(result.getResultData().getProcessOutputs().getTaskkey());
                }
            }
            if (tran==null){
                return m;
            }
            errortext=InforWasExchangeSupport.errorMessage(result);
            if (errortext.length()>700){
                errortext=errortext.substring(0, 700);
            }
            if (!repost){
                m = this.createEdiTrans(tran, errortext, worker);
            }else{
                etrans=this.dyncdataQueryService.queryEdiTransByTransId(tran.getId());
                if ((etrans!=null) && (etrans.size()>0)){
                    m = this.updateEdiTransData(etrans.get(0), worker,  "", errortext);
                }
            }
            if (!StringUtils.isNullOrBlank(m)){
                return m;
            }
            if (StringUtils.isNullOrBlank(errortext)){
                tran.setEdiSendTime(new Date());
            }
            this.updateEdiTransData(tran, worker, errortext);
            this.transService.save(tran);
        }catch (Exception e){
            e.printStackTrace();
        }
        return m;
    }


/**==================================================================================================================**/
// ---- WAS-XWMS/CALL
/**==================================================================================================================**/
    //
    public List<FuncReplyData<TaskReportResultDto>> handleWasTransTaskToXwms(String divisionCode, List<TwtActTaskList> tasks){
        return inforCommonWorkService.reportTask(divisionCode, tasks);
    }

    /**
    public List<FuncReplyData<TaskReportResultDto>> sendWasTransReportToXwms(String divisionCode, List<TaskReportData> taskReports){
        return inforCommonWorkService.reportTaskData(divisionCode, taskReports);
    }
    **/

    public List<FuncReplyData<TaskReportResultDto>> handleWasTransDataToXwms(List<Long> tranIds, boolean repost, String worker){
        TaskReportData reportData=null;
        FuncReplyData<TaskReportResultDto> resultData=null;
        List<FuncReplyData<TaskReportResultDto>> resultDatas=new ArrayList<>();
        TwtActTransList tran=null;
        String divisionCode=null;
        String m = "";
        try{
            for (Long id:tranIds){
                if (id==null){
                    continue;
                }
                tran=this.transService.findById(id);
                if (tran==null){
                    m="找不到交易,请确认是否已经取消或删除.ID:"+String.valueOf(id);
                    resultDatas.add(InforWasExchangeSupport.errorReply(m));
                    return resultDatas;
                }
                if ((!WmsConstants.TRANS_TYPE_RECEIVE.equalsIgnoreCase(tran.getType()))
                        && (!WmsConstants.TRANS_TYPE_SHIP.equalsIgnoreCase(tran.getType()))){
                    m="非有效的交易类型.交易号:"+tran.getNumber();
                    resultDatas.add(InforWasExchangeSupport.errorReply(m));
                    return resultDatas;
                }
                if (CodesConstants.COMMON_STATUS_CANCELLED.equalsIgnoreCase(tran.getTransStatus())){
                    m="交易已经取消,不能上传.交易号:"+tran.getNumber();
                    resultDatas.add(InforWasExchangeSupport.errorReply(m));
                    return resultDatas;
                }
                if ((!StringUtils.isNullOrBlank(tran.getUdf11()))
                        && (!InforWasXcmgExchangeConstants.SYS_XWMS.equalsIgnoreCase(tran.getUdf11()))){
                    m="非INFOR来源数据,不需要上传上传.交易号:"+tran.getNumber();
                    resultData = InforWasExchangeSupport.errorReply(m);
                    return resultDatas;
                }
                /**
                if (CodesConstants.COMMON_STATUS_CLOSED.equalsIgnoreCase(tran.getEdiSendStatus())){
                    m="交易已经标记为上传成功.交易号:"+tran.getNumber();
                    resultDatas.add(InforWasExchangeSupport.errorReply(m));
                    return resultDatas;
                }
                 **/
                resultData = handleWasTransDataToXwms(tran, repost, worker);
                if (resultData!=null){
                    resultDatas.add(resultData);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultDatas;
    }

    public FuncReplyData<TaskReportResultDto> handleWasTransDataToXwms(TwtActTransList trans, boolean repost, String worker){
        TaskReportData reportData=null;
        FuncReplyData<TaskReportResultDto> resultData=null;
        if (trans==null){
            return resultData;
        }
        String divisionCode=null;
        String m = "";
        try{
            if (trans==null){
                m="找不到交易,请确认是否已经取消或删除.";
                resultData = InforWasExchangeSupport.errorReply(m);
                return resultData;
            }
            if ((!WmsConstants.TRANS_TYPE_RECEIVE.equalsIgnoreCase(trans.getType()))
                    && (!WmsConstants.TRANS_TYPE_SHIP.equalsIgnoreCase(trans.getType()))){
                m="非有效的交易类型.交易号:"+trans.getNumber();
                resultData = InforWasExchangeSupport.errorReply(m);
                return resultData;
            }
            if (CodesConstants.COMMON_STATUS_CANCELLED.equalsIgnoreCase(trans.getTransStatus())){
                m="交易已经取消,不能上传.交易号:"+trans.getNumber();
                resultData = InforWasExchangeSupport.errorReply(m);
                return resultData;
            }
            if (StringUtils.isNullOrBlank(trans.getUdf11())){
                resultData = InforWasExchangeSupport.emptyReply();
                return resultData;
            }
            if ((!StringUtils.isNullOrBlank(trans.getUdf11()))
                    && (!InforWasXcmgExchangeConstants.SYS_XWMS.equalsIgnoreCase(trans.getUdf11()))){
                m="非INFOR来源数据,不需要上传上传.交易号:"+trans.getNumber();
                //resultData = InforWasExchangeSupport.errorReply(m);
                resultData = InforWasExchangeSupport.emptyReply();
                return resultData;
            }
            /**
             if (CodesConstants.COMMON_STATUS_CLOSED.equalsIgnoreCase(tran.getEdiSendStatus())){
                 m="交易已经标记为上传成功.交易号:"+tran.getNumber();
                 resultData = InforWasExchangeSupport.errorReply(m);
                 return resultData;
             }
             **/
            reportData=this.inforCommonWorkService.translateTo(divisionCode, trans);
            if (reportData!=null){
                resultData=this.inforCommonWorkService.reportTaskData(divisionCode, reportData);
                m = this.saveEdiSendChange(trans, resultData, repost, worker);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultData;
    }

    public List<FuncReplyData<TaskReportResultDto>> handleWasEdiTransDataToXwms(List<Long> tranIds, boolean repost, String notes, String worker){
        FuncReplyData<TaskReportResultDto> resultData=null;
        List<FuncReplyData<TaskReportResultDto>> resultDatas=new ArrayList<>();
        TwiActTransList tran=null;
        String m = "";
        try{
            for (Long id:tranIds){
                if (id==null){
                    continue;
                }
                tran=this.ediTransactionService.findById(id);
                if (tran==null){
                    m="找不到交易,请确认是否已经取消或删除.ID:"+String.valueOf(id);
                    resultDatas.add(InforWasExchangeSupport.errorReply(m));
                    return resultDatas;
                }
                if ((!WmsConstants.TRANS_TYPE_RECEIVE.equalsIgnoreCase(tran.getTransType()))
                        && (!WmsConstants.TRANS_TYPE_SHIP.equalsIgnoreCase(tran.getTransType()))){
                    m="非有效的交易类型.交易号:"+tran.getTransNumber();
                    resultDatas.add(InforWasExchangeSupport.errorReply(m));
                    return resultDatas;
                }
                if (CodesConstants.COMMON_STATUS_CANCELLED.equalsIgnoreCase(tran.getEdiReceiveStatus())){
                    m="交易已经取消,不能上传.交易号:"+tran.getTransNumber();
                    resultDatas.add(InforWasExchangeSupport.errorReply(m));
                    return resultDatas;
                }
                if ((!StringUtils.isNullOrBlank(tran.getUdf11()))
                        && (!InforWasXcmgExchangeConstants.SYS_XWMS.equalsIgnoreCase(tran.getUdf11()))){
                    m="非INFOR来源数据,不需要上传上传.交易号:"+tran.getTransNumber();
                    resultData = InforWasExchangeSupport.errorReply(m);
                    return resultDatas;
                }
                /**
                 if (CodesConstants.COMMON_STATUS_CLOSED.equalsIgnoreCase(tran.getEdiSendStatus())){
                 m="交易已经标记为上传成功.交易号:"+tran.getNumber();
                 resultDatas.add(InforWasExchangeSupport.errorReply(m));
                 return resultDatas;
                 }
                 **/
                resultData = handleWasTransDataToXwms(tran, repost, notes, worker);
                if (resultData!=null){
                    resultDatas.add(resultData);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultDatas;
    }

    public FuncReplyData<TaskReportResultDto> handleWasTransDataToXwms(TwiActTransList trans, boolean repost, String notes, String worker){
        TaskReportData reportData=null;
        FuncReplyData<TaskReportResultDto> resultData=null;
        if (trans==null){
            return resultData;
        }
        String divisionCode=null;
        String m = "";
        try{
            if (trans==null){
                m="找不到交易,请确认是否已经取消或删除.";
                resultData = InforWasExchangeSupport.errorReply(m);
                return resultData;
            }
            if ((!WmsConstants.TRANS_TYPE_RECEIVE.equalsIgnoreCase(trans.getTransType()))
                    && (!WmsConstants.TRANS_TYPE_SHIP.equalsIgnoreCase(trans.getTransType()))){
                m="非有效的交易类型.交易号:"+trans.getTransNumber();
                resultData = InforWasExchangeSupport.errorReply(m);
                return resultData;
            }
            if (CodesConstants.COMMON_STATUS_CANCELLED.equalsIgnoreCase(trans.getEdiReceiveStatus())){
                m="交易已经取消,不能上传.交易号:"+trans.getTransNumber();
                resultData = InforWasExchangeSupport.errorReply(m);
                return resultData;
            }
            if ((!StringUtils.isNullOrBlank(trans.getUdf11()))
                    && (!InforWasXcmgExchangeConstants.SYS_XWMS.equalsIgnoreCase(trans.getUdf11()))){
                m="非INFOR来源数据,不需要上传上传.交易号:"+trans.getTransNumber();
                resultData = InforWasExchangeSupport.errorReply(m);
                return resultData;
            }

            /**
             if (CodesConstants.COMMON_STATUS_CLOSED.equalsIgnoreCase(tran.getEdiSendStatus())){
             m="交易已经标记为上传成功.交易号:"+tran.getNumber();
             resultData = InforWasExchangeSupport.errorReply(m);
             return resultData;
             }
             **/
            reportData=this.inforCommonWorkService.translateTo(divisionCode, trans);
            if (reportData!=null){
                resultData=this.inforCommonWorkService.reportTaskData(divisionCode, reportData);
                m = this.saveEdiSendChange(trans, resultData, repost, notes, worker);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultData;
    }


/**==================================================================================================================**/
// ---- WAS-WCS/CALL
/**==================================================================================================================**/

    public String sendWasTaskToWcs(List<TwtActTaskList> tasks, String batchNumber, String worker){
        String m = "";

        if ((tasks==null)||(tasks.size()==0)){
            return m;
        }
        if (StringUtils.isNullOrBlank(m)){
            batchNumber = TextUtils.genBatchNumber();
        }
        TaskActionDto actionDto=null;
        CommonResultData commonResultData=null;
        Map<String, String> containers=new HashedMap();
        String mline="";
        int errorcount=0;
        LocationLineDto fmloc=null;
        try {
            actionDto = new TaskActionDto();
            actionDto.setBatchNumber(batchNumber);
            actionDto.setWorker(worker);
            for (TwtActTaskList t : tasks) {
                if (t == null) {
                    errorcount++;
                    mline= "找不到任务,请确认是否已删除." ;
                    if (errorcount<4){
                        m=m+mline+","+"\r\n";
                    }
                    continue;
                }
                if (WmsConstants.TASK_STATUS_CLOSE.equalsIgnoreCase(t.getStatus())) {
                    errorcount++;
                    mline = "任务已关闭.任务号:" + t.getNumber();
                    if (errorcount<4){
                        m=m+mline+","+"\r\n";
                    }
                    continue;
                }
                if (WmsConstants.TASK_STATUS_CANCEL.equalsIgnoreCase(t.getStatus())) {
                    errorcount++;
                    m = "任务已取消.任务号:" + t.getNumber();
                    if (errorcount<4){
                        m=m+mline+","+"\r\n";
                    }
                    continue;
                }
                if (WmsConstants.TASK_STATUS_EDI_CLOSE.equalsIgnoreCase(t.getStatus())) {
                    errorcount++;
                    m = "任务已设备执行完成.任务号:" + t.getNumber();
                    if (errorcount<4){
                        m=m+mline+","+"\r\n";
                    }
                    continue;
                }
                if (WmsConstants.TASK_STATUS_EDI_WORKING.equalsIgnoreCase(t.getStatus())) {
                    //重置状态,用于重新下发
                    t.setStatus(WmsConstants.TASK_STATUS_CREATE);
                    this.taskService.save(t);
                }
                if (containers.containsKey(t.getFromContainNumber())){
                    continue;
                }

                //
                if (WmsConstants.TASK_TYPE_PICK.equalsIgnoreCase(t.getType())){
                    fmloc=this.locationResolver.lookup(t.getFromLocId());
                    if (!WmsConstants.LOCATION_TYPE_BIN.equalsIgnoreCase(fmloc.getLocationType())){
                        continue;
                    }
                    //
                    if (this.wcsCustomWorkApiService.containerAtOutside(t.getFromContainNumber())){
                        continue;
                    }
                }
                commonResultData = this.wcsCustomWorkService.execute(Arrays.asList(t), actionDto);
                mline= WcsWasExchangeSupport.errorText(commonResultData);
                if (StringUtils.isNullOrBlank(mline)){
                    this.changeTaskStatus(Arrays.asList(t), WmsConstants.TASK_STATUS_PULLED_DOWN, "", worker);
                }else {
                    this.changeTaskStatus(Arrays.asList(t), WmsConstants.TASK_STATUS_EDI_FAILED, mline, worker);
                    errorcount++;
                    if (errorcount<4){
                        m=m+mline+","+"\r\n";
                    }
                }
                containers.put(t.getFromContainNumber(), t.getNumber());
            }
        }catch (Exception e){
            m = "释放任务失败.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    public String sendWasTaskToWcsBatch(List<TwtActTaskList> tasks, String batchNumber, String worker){
        String m = "";

        if ((tasks==null)||(tasks.size()==0)){
            return m;
        }
        if (StringUtils.isNullOrBlank(m)){
            batchNumber = TextUtils.genBatchNumber();
        }
        TaskActionDto actionDto=null;
        CommonResultData commonResultData=null;
        try {
            for (TwtActTaskList t : tasks) {
                if (t == null) {
                    m = "找不到任务,请确认是否已删除.:" ;
                    return m;
                }
                if (WmsConstants.TASK_STATUS_CLOSE.equalsIgnoreCase(t.getStatus())) {
                    m = "任务已关闭.任务号:" + t.getNumber();
                    return m;
                }
                if (WmsConstants.TASK_STATUS_CANCEL.equalsIgnoreCase(t.getStatus())) {
                    m = "任务已取消.任务号:" + t.getNumber();
                    return m;
                }
                if (WmsConstants.TASK_STATUS_EDI_WORKING.equalsIgnoreCase(t.getStatus())) {
                    //重置状态,用于重新下发
                    t.setStatus(WmsConstants.TASK_STATUS_CREATE);
                    this.taskService.save(t);
                }
            }
            actionDto = new TaskActionDto();
            actionDto.setBatchNumber(batchNumber);
            actionDto.setWorker(worker);
            commonResultData = this.wcsCustomWorkService.execute(tasks, actionDto);
            m= WcsWasExchangeSupport.errorText(commonResultData);
            if (StringUtils.isNullOrBlank(m)){
                this.changeTaskStatus(tasks, WmsConstants.TASK_STATUS_PULLED_DOWN, "", worker);
            }else {
                this.changeTaskStatus(tasks, WmsConstants.TASK_STATUS_EDI_FAILED, m, worker);
            }
        }catch (Exception e){
            m = "释放任务失败.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }



/**==================================================================================================================**/
// ---- WAS-SAP/CALL
/**==================================================================================================================**/
    public List<DeliveryNoteTransReplyData> handleWasTransDataToSap(List<Long> tranIds, boolean repost, String worker){
        List<DeliveryNoteTransReplyData> resultDatas=new ArrayList<>();
        return resultDatas;
    }

/**==================================================================================================================**/
// ---- WAS-MES/CALL
/**==================================================================================================================**/
    public String queryKitDocument(String doumentNumber){
        String m = "";
        if (StringUtils.isNullOrBlank(doumentNumber)){
            return m;
        }
        KitDocumentReplyData replyData=null;
        List<KitDocumentLineReplyData> lines=null;
        TwiDocMesKitDocline docline=null;
        try{
            replyData=this.mesCustomWorkService.query(XcmgAmConstants.DIVISION_WH101_ID, doumentNumber);
            if (replyData==null){
                m="获取配盘单出错.请确认MES接口开启。单号:"+doumentNumber;
                return m;
            }
            if ((!MesWasXcmgExchangeConstants.RESULT_STATUS_SUCCESS.equalsIgnoreCase(replyData.getStatus()))
                 || (!MesWasXcmgExchangeConstants.RESULT_STATUS_CODE_SUCCESS.equalsIgnoreCase(replyData.getCode()))){
                m="获取配盘单出错.";
                if (!StringUtils.isNullOrBlank(replyData.getErrMsg())){
                    m=replyData.getErrMsg();
                }
                m=replyData.getCode()+"/"+m;
                return m;
            }
            lines=replyData.getInfo();
            if ((lines==null)||(lines.size()==0)){
                m="获取配盘单出错,缺少行数据.";
                return m;
            }
            for (KitDocumentLineReplyData d:lines){
                m= MesWasExchangeSupport.check(d);
                if (!StringUtils.isNullOrBlank(m)){
                    return m;
                }
            }
            for (KitDocumentLineReplyData d:lines){
                docline=this.translateTo(d);
                if (docline!=null){
                    this.mesKitDocklineService.save(docline);
                }
            }
        }catch (Exception e){
            m="获取MES配盘单数据出错.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    private TwiDocMesKitDocline translateTo(KitDocumentLineReplyData lineData){
        TwiDocMesKitDocline docline=null;
        if (lineData==null){
            return docline;
        }
        BigDecimal qty=BigDecimal.ONE;
        docline=new TwiDocMesKitDocline();
        docline.setGlobalClientId(XcmgAmConstants.CLIENT_ID_XCMG);
        docline.setCustomerId(XcmgAmConstants.CUSTOMER_ID_XCMG_AM);
        docline.setDivisionId(XcmgAmConstants.DIVISION_WH101_ID);
        docline.setDocumentNumber(lineData.getPollNo());
        docline.setDocumentLinenumber(lineData.getPrecNo());
        docline.setMaterialId(null);
        docline.setMaterialCode(lineData.getCompNo());
        docline.setMaterialName(lineData.getCompName());
        docline.setOrderedQty(BigDecimal.ONE);
        qty=StringUtils.getBigdecimalValue(lineData.getAskNum());
        if (qty!=null){
            docline.setOrderedQty(qty);
        }
        docline.setOrderedQtyEach(docline.getOrderedQty());
        docline.setSortationLocCode(lineData.getKbType());
        docline.setSortationLocName(lineData.getKbTypeName());
        docline.setLineCode(lineData.getLineno());
        docline.setUloc(lineData.getWorkid());
        docline.setDocWbsNum(lineData.getField1());
        docline.setContainerNumber(lineData.getField2());
        docline.setAgvType(lineData.getField3());
        docline.setAgvParams(lineData.getField4());
        docline.setAgvLoad(lineData.getField5());
        docline.setAgvTaskNumber(lineData.getResarea());
        docline.setDeliveryTime(lineData.getAskArrtime());
        docline.setIszsType(lineData.getIszsType());
        docline.setPlatCon(lineData.getPlatCon());
        docline.setCreateSource(CodesConstants.SYSTEM_MES);
        docline.setLoadStatus(CodesConstants.COMMON_STATUS_CREATED);
        docline.setCheckStatus(CodesConstants.COMMON_STATUS_CREATED);
        docline.setUdf01(lineData.getField1());
        docline.setUdf02(lineData.getField2());
        docline.setUdf03(lineData.getField3());
        docline.setUdf04(lineData.getField4());
        docline.setUdf05(lineData.getField5());
        docline.setUdf06(lineData.getField6());
        docline.setUdf07(lineData.getField7());
        docline.setUdf08(lineData.getField8());
        docline.setUdf09(lineData.getField9());
        docline.setUdf10(lineData.getField10());
        docline.setEnabled(true);
        docline.setEditable(false);
        docline.setCreatedBy(CodesConstants.SYSTEM_USER_MES);
        docline.setCreatedDate(new Date());
        docline.setLastModifiedBy(docline.getCreatedBy());
        docline.setLastModifiedDate(docline.getCreatedDate());
        return docline;
    }

/**==================================================================================================================**/
// ---- CUSTOM/II/INBOUND
/**==================================================================================================================**/

    public String checkKitAsnSave(TwaDocAsnHeader doc){
        String m = "";
        if (doc==null){
            m="配盘入库单数据为空.";
            return m;
        }
        if (StringUtils.isNullOrBlank(doc.getDeliveryContainerNum())){
            m="请扫描绑定有效的托盘码.";
            return m;
        }
        doc.setDeliveryContainerNum(doc.getDeliveryContainerNum().trim());
        List<TwaInventoryDetails> storages=null;
        List<TwtActTaskList> tasks=null;
        List<TwtActPalletizeList> pals=null;
        List<TwaDocAsnHeader> headers=null;
        try{
            storages=this.inventoryService.findByContainNumber(doc.getDeliveryContainerNum());
            if ((storages!=null) && (storages.size()>0)){
                m="托盘已经绑定库存，请确认是否托盘码重复.托盘码:"+doc.getDeliveryContainerNum();
                return m;
            }
            tasks=this.taskService.queryWorkingTasks("", doc.getDeliveryContainerNum());
            if ((tasks!=null)&& (tasks.size()>0)){
                m="托盘关联有任务正在执行，请确认是否托盘码重复.托盘码:"+doc.getDeliveryContainerNum();
                return m;
            }
            pals=this.palletizeService.query(doc.getDeliveryContainerNum(), false);
            if ((pals!=null)&& (pals.size()>0)){
                m="托盘已经存在码盘数据，请确认是否托盘码重复.托盘码:"+doc.getDeliveryContainerNum();
                return m;
            }
            headers=this.dyncdataQueryService.queryAsnHeader(null, doc.getDeliveryContainerNum());
            if ((headers!=null)||(headers.size()>0)){
                for (TwaDocAsnHeader h:headers){
                    if (h==null){
                        continue;
                    }
                    if (WmsConstants.ASN_STATUS_RECEIVE.compareToIgnoreCase(h.getStatus())>0){
                        if (InforWasXcmgExchangeConstants.SYS_XWMS.equalsIgnoreCase(h.getCreateSource())){
                            m="托盘已经存在采购码盘入库单，请确认是否托盘码重复或已完成入库单尚未关闭.托盘码:"+doc.getDeliveryContainerNum();
                        }
                        if (CodesConstants.SYSTEM_WMS.equalsIgnoreCase(h.getCreateSource())){
                            m="托盘已经配盘，不能重复绑定。或检查托盘码是否重复、已完成入库单未关闭。托盘码:"+doc.getDeliveryContainerNum()+".入库单号:"+h.getDocumentNumber();
                        }
                        return m;
                    }
                }
                return m;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return m;
    }

    public String populateKitAsn(TwaDocAsnHeader header, String worker){
        String m = "";
        if (header==null){
            m="配盘入库单数据为空.";
            return m;
        }
        header.setUdf01(null);
        header.setUdf02(null);
        //配盘单号
        header.setUdf03(header.getDeliveryShipNum());
        //产线
        header.setUdf04(header.getPlanUnloadPlace());
        //工位
        header.setUdf05(header.getPlanUnloadDoor());
        //
        header.setUdf06(header.getDeliveryFromPlace());
        //批次
        header.setUdf07(header.getDeliveryTerms());

        return m;
    }

    public String populateSmAsn(TwaDocAsnHeader header, String worker){
        String m = "";
        if (header==null){
            m="配盘入库单数据为空.";
            return m;
        }

        return m;
    }



/**==================================================================================================================**/
// ---- CUSTOM/II/OUTBOUND
/**==================================================================================================================**/

    public List<TwtActTaskList> sortPickTaskPickSequence(List<TwtActTaskList> source){
        return source;
    }

    public List<TwtActTaskList> sortCountTaskCountingSequence(List<TwtActTaskList> source){
        return source;
    }


    public String addtoKitSoByInventory(String batchNumber, Long storageId, String worker){
        return this.makeKitSoByInventory(batchNumber, storageId, false, worker);
    }

    public String createKitSoByInventory(String batchNumber, Long storageId, String worker){
        return this.makeKitSoByInventory(batchNumber, storageId, true, worker);
    }

    public String makeKitSoByInventory(String batchNumber, Long storageId, boolean createNew, String worker){
        String m = "";
        if (storageId==null){
            return m;
        }
        TwaInventoryDetails storage=null;
        TwaDocSoHeader header=null;
        TaskActionDto actionDto=null;
        List<TwaDocSoHeader> headers=null;
        try{
            storage=this.inventoryService.findById(storageId);
            m=this.checkKitInventoryOutbound(storage, storageId);
            if (!StringUtils.isNullOrBlank(m)){
                return m;
            }
            if (!createNew){
                headers=this.dyncdataQueryService.openLastSoDocument(storage.getDivisionId(), XcmgAmConstants.WORK_SOURCE_KIT);
                if ((headers!=null) && (headers.size()>0)){
                    header=headers.get(0);
                }
            }
            if (header==null){
                header=this.takeSoHeader(storage, XcmgAmConstants.WORK_SOURCE_KIT, worker);
                if (header!=null){
                    this.soService.save(header);
                }
            }
            actionDto=new TaskActionDto();
            actionDto.setBatchNumber(batchNumber);
            actionDto.setWorker(worker);
            m=this.createKitSoDetails(header, storage, actionDto);

            //
            if (StringUtils.isNullOrBlank(m)){
                storage.setReserveDocNumber(header.getDocumentNumber());
                storage.setLastModifiedBy(worker);
                storage.setLastModifiedDate(new Date());
                this.inventoryService.save(storage);
            }
        }catch (Exception e){
            m="追加出库失败.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    private String createKitSoDetails(TwaDocSoHeader header, TwaInventoryDetails storage, TaskActionDto actionDto){
        String m = "";
        if (header==null){
            return m;
        }
        if (storage==null){
            return m;
        }
        if (actionDto==null){
            actionDto=new TaskActionDto();
        }
        if (StringUtils.isNullOrBlank(actionDto.getBatchNumber())){
            actionDto.setBatchNumber(TextUtils.genBatchNumber());
        }
        if (StringUtils.isNullOrBlank(actionDto.getWorker())){
            actionDto.setWorker(SecurityUtils.getLoginUsername());
        }
        if (!WmsConstants.SO_STATUS_CREATE.equalsIgnoreCase(header.getStatus())){
            m="出库单非创建状态,不能追加出库明细行.单号:"+header.getDocumentNumber();
            return m;
        }
        if (header.getWaveId()!=null){
            m="出库单已经生成波次,不能追加出库明细.单号:"+header.getDocumentNumber();
            return m;
        }
        TwaDocSoDetails line=null;
        try{
            line=this.createSoDetails(header, storage);
            if (line!=null){
                this.soDetailsService.save(line);
            }
        }catch (Exception e){
            m="追加出库失败.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    public String loadSelfMadeSoDocuemnts(String divisionCode, List<DeliveryNoteData> deliveryNoteDatas, String worker){
        String m = "";
        if ((deliveryNoteDatas==null)||(deliveryNoteDatas.size()==0)){
            return m;
        }
        Long divisionId=this.divisionService.retrieveOn(divisionCode, XcmgAmConstants.DIVISION_WH101_ID);
        if (StringUtils.isNullOrBlank(worker)){
            worker=SecurityUtils.getLoginUsername();
        }
        for (DeliveryNoteData d:deliveryNoteDatas){
            m = this.check(d);
            if (!StringUtils.isNullOrBlank(m)){
                return m;
            }
            d.setAufnr(d.getAufnr().trim());
            d.setMatnr(d.getMatnr().trim());
        }
        TwaDocSoHeader header=null;
        Map<String, TwaDocSoHeader> headers=new HashMap<>();
        TwaDocSoDetails line=null;
        String docnum=null;
        Map<Long, Integer> nextlinenum=new HashedMap();
        Integer lineindex=null;
        TwmBasMaterial material=null;
        try{
            for (DeliveryNoteData dn:deliveryNoteDatas){
                docnum=dn.getZpszlnum();
                header=headers.get(docnum);
                if (header==null){
                    header=this.takeSoHeader(dn);
                    if (header!=null){
                        if (XcmgAmConstants.WORK_SOURCE_SELF_MADE.equalsIgnoreCase(header.getCategory())){
                            m="非自制件订单,请联系系统管理员.单号:"+docnum;
                            return m;
                        }
                        //暂时方案
                        if (!WmsConstants.SO_STATUS_CREATE.equalsIgnoreCase(header.getStatus())){
                            m="自制件订单非创建状态,不能追加导入.单号:"+docnum;
                            return m;
                        }
                    }
                    if (header==null){
                        if (SapWasXcmgExchangeSupport.isDelete(dn)){
                            continue;
                        }
                        if (SapWasXcmgExchangeSupport.isClose(dn)){
                            continue;
                        }
                        header=this.createSmSoHeader(divisionId, dn, worker);
                        if (header==null){
                            m="创建自制件出库单失败.";
                            return m;
                        }
                        headers.put(header.getDocumentNumber(), header);
                    }
                }
                material=this.materialService.lookup(XcmgAmConstants.CUSTOMER_CODE_XCMG_AM, dn.getMatnr());
                if (material==null){
                    //
                }
                //
                if (StringUtils.isNullOrBlank(dn.getZpszlhzpos())){
                    if (SapWasXcmgExchangeSupport.isDelete(dn)){
                        continue;
                    }
                    if (SapWasXcmgExchangeSupport.isClose(dn)){
                        continue;
                    }
                    lineindex = nextlinenum.get(header.getId());
                    if (lineindex==null){
                        lineindex=this.soDetailsService.maxLineNumber(header.getId());
                        if (lineindex<=0){
                            lineindex=0;
                        }
                        if (lineindex>10){
                            lineindex=lineindex /10;
                        }
                    }
                    lineindex++;
                    line=this.createSoDetails(header, dn, material, lineindex);
                    if (line!=null){
                        this.soDetailsService.save(line);
                        nextlinenum.put(header.getId(), lineindex);
                    }
                }
                //
                if (!StringUtils.isNullOrBlank(dn.getZpszlhzpos())){
                    dn.setZpszlhzpos(dn.getZpszlhzpos().trim());
                    line=this.soDetailsService.findByDocumentLine(header.getId(), dn.getZpszlhzpos());
                    if (line!=null){
                        if (!WmsConstants.SO_STATUS_CREATE.equalsIgnoreCase(line.getLineStatus())){
                            this.deliveryNoteLoadError(dn, header, line, "订单行非创建状态,不能修改.");
                            continue;
                        }
                        if (line.getWaveDetailsId()!=null){
                            this.deliveryNoteLoadError(dn, header, line, "订单行已经创建波次,不能修改.");
                            continue;
                        }
                        if (SapWasXcmgExchangeSupport.isDelete(dn)){
                            this.soDetailsService.delete(line);
                            continue;
                        }
                        if (SapWasXcmgExchangeSupport.isClose(dn)){
                            this.soDetailsService.save(line);
                            continue;
                        }
                        this.updateSodetails(dn, header, line, material);
                    }
                    if (line==null){
                        line=this.createSoDetails(header, dn, material, 0);
                        if (line!=null){
                            this.soDetailsService.save(line);
                        }
                    }
                }
            }
        }catch (Exception e){
            m="导入配送指令出错.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    private String updateSodetails(DeliveryNoteData deliveryNoteData, TwaDocSoHeader header, TwaDocSoDetails line, TwmBasMaterial material){
        String m = "";
        if (deliveryNoteData==null){
            return m;
        }
        if (line==null){
            return m;
        }
        try{
            if (material!=null) {// && (!line.getMaterialId().equals(material.getId()))){
                line.setMaterialId(material.getId());
            }
            this.populateSoDetails(line, deliveryNoteData, header, material);
            line.setQtyOrdered(deliveryNoteData.getZpssl());
            line.setQtyOrderedEach(line.getQtyOrdered());
            line.setLastModifiedDate(new Date());
            line.setLastModifiedBy(SapWasXcmgExchangeConstants.SAP_USER_NAME);
        }catch (Exception e){
            e.printStackTrace();
        }
        return m;
    }

    private String deliveryNoteLoadError(DeliveryNoteData deliveryNoteData, TwaDocSoHeader header, TwaDocSoDetails line, String errorText){
        String m="";
        return m;
    }

    public String checkKitInventory(TwaInventoryDetails storage, Long storageId){
        String m = "";
        if (storage==null){
            m="找不到配盘件库存,请确认是否已经删除或出库。库存Id:"+String.valueOf(storageId);
            return m;
        }
        if (StringUtils.isNullOrBlank(storage.getReserveCode())){
            m="非配盘件.";
            return m;
        }
        if (!XcmgAmConstants.WORK_SOURCE_KIT.equalsIgnoreCase(storage.getReserveCode())){
            m="非配盘件.";
            return m;
        }
        if (!XcmgAmConstants.MATERIAL_ID_KIT.equals(storage.getMaterialId())){
            m="非配盘件.";
            return m;
        }
        return m;
    }

    public String checkKitInventoryOutbound(TwaInventoryDetails storage, Long storageId){
        String m = this.checkKitInventory(storage, storageId);
        if (!StringUtils.isNullOrBlank(m)){
            return m;
        }
        if ((storage.getQtyAllocated()!=null) && (storage.getQtyAllocated().compareTo(BigDecimal.ZERO)>0)){
            m="配盘件已经分配出库.";
            return m;
        }
        if (!StringUtils.isNullOrBlank(storage.getReserveDocNumber())){
            m="配盘件已经分配出库.单号:"+storage.getReserveDocNumber();
            return m;
        }
        List<TwtActTaskList> tasks=null;
        try{
            tasks=this.taskService.queryWorkingTasks("", storage.getContainNumber());
            if ((tasks!=null) && (tasks.size()>0)){
                m="配盘件正在作业中.托盘码:"+storage.getContainNumber()+",任务号:"+tasks.get(0).getNumber();
                return m;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return m;
    }

    public String check(DeliveryNoteData dn){
        String m = "";
        if (dn==null){
            m="无效的配送指令.";
            return m;
        }
        if (StringUtils.isNullOrBlank(dn.getAufnr())){
            m="无效的配送指令,订单编号为空.";
            return m;
        }
        if (StringUtils.isNullOrBlank(dn.getMatnr())){
            m="无效的配送指令,物料编号为空.";
            return m;
        }
        if (dn.getZpssl()==null){
            m="无效的配送指令,配送数量为空.";
            return m;
        }
        if (dn.getZpssl().compareTo(BigDecimal.ZERO)<=0){
            m="无效的配送指令,配送数量必须大于0.";
            return m;
        }
        return m;
    }

    public TwaDocSoHeader takeSoHeader(DeliveryNoteData deliveryNoteData){
        TwaDocSoHeader header=null;
        if (deliveryNoteData==null){
            return header;
        }
        if (StringUtils.isNullOrBlank(deliveryNoteData.getZpszlnum())){
            return header;
        }
        header=this.soService.findByDocumentNumber(deliveryNoteData.getZpszlnum());
        //CHECK DOC-CATE
        return header;
    }

    public TwaDocSoHeader createSmSoHeader(Long divisionId, DeliveryNoteData deliveryNoteData, String worker){

        TwaDocSoHeader header=new TwaDocSoHeader();
        header.setDocumentNumber(deliveryNoteData.getZpszlnum());
        header.setGlobalClientId(XcmgAmConstants.CLIENT_ID_XCMG);
        //header.setCustomerId(XcmgAmConstants.CUSTOMER_ID_XCMG_AM);
        header.setDivisionId(divisionId);
        header.setCategory(null);
        header.setType(WmsConstants.SO_TYPE_WORK_ORDER);
        header.setStatus(WmsConstants.SO_STATUS_CREATE);


        //分组唯一码
        header.setDeliveryTerms(null);

        //外购,自制,非生产,其它
        header.setCategory(XcmgAmConstants.WORK_SOURCE_SELF_MADE);

        //外部单号
        //header.setRefDocNumber(storage.getUdf03());
        header.setRefDocNumber(null);
        //工单号
        header.setRefAsnNumber(null);
        //出库单号
        header.setRefSoNumber(null);
        //WBS
        header.setPaymentTerms(null);

        //分厂
        header.setConsigneeName(null);
        //产线
        header.setPlanLoadPlace(null);             //storage.getUdf04());
        //工位
        header.setPlanLoadDoor(null);             //storage.getUdf05());
        //配盘点
        header.setDeliveryFromPlace(null);        //storage.getUdf06());

        //WBS
        header.setUdf03(null);
        //
        header.setHEdi03(null);      //storage.getUdf03()                 //外部单号
        header.setHEdi04(null);                                           //订单号
        header.setHEdi05(null);                                           //出库单号
        header.setHEdi06(null);                                           //分厂
        header.setHEdi07(null);      //storage.getUdf04());               //产线
        header.setHEdi08(null);      //storage.getUdf05());               //工位

        header.setCreateSource(CodesConstants.SYSTEM_ERP);
        header.setDocPrior(WmsConstants.TASK_PRIOR_NORMAL);

        header.setEnabled(true);
        header.setEditable(true);
        header.setDelFlag(false);

        header.setCreatedDate(new Date());
        header.setCreatedBy(worker);
        header.setLastModifiedDate(header.getCreatedDate());
        header.setLastModifiedBy(header.getCreatedBy());

        return header;
    }

    public boolean livePickMode(){
        if (StringUtils.isNullOrBlank(XcmgAmConstants.PICK_ZONE_CHECK_MODE)){
            return false;
        }
        if (!XcmgAmConstants.PICK_ZONE_CROSS_CHECK_MODE_FORBID.equalsIgnoreCase(XcmgAmConstants.PICK_ZONE_CHECK_MODE)) {
            return false;
        }
        return true;
    }

    public List<TwtActAllocationList> livePickFilter(String containerNumber, List<TwtActAllocationList> picks){
        if (!this.livePickMode()){
            return picks;
        }
        if ((picks==null) || (picks.size()==0)){
            return picks;
        }
        if (StringUtils.isNullOrBlank(containerNumber)){
            return picks;
        }
        containerNumber=containerNumber.trim();
        //
        TwtActAllocationList t=null;
        String czonecode=null;
        String pzonecode=null;
        Iterator<TwtActAllocationList> it=null;
        try{
            czonecode=this.currentZone(containerNumber);
            if (!XcmgAmConstants.onlinePickZoneMap.containsKey(czonecode)){
                return picks;
            }
            it=picks.iterator();
            while(it.hasNext()){
                t=it.next();
                pzonecode=this.locationZone(t.getToLocId());
                if (StringUtils.isNullOrBlank(pzonecode)){
                    continue;
                }
                if (XcmgAmConstants.onlinePickZoneMap.containsKey(pzonecode)){
                    if (!pzonecode.equalsIgnoreCase(czonecode)){
                        it.remove();
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return picks;
    }



/**==================================================================================================================**/
// ---- CUSTOM/II/INVENTORY
/**==================================================================================================================**/
    public String transfer(LotattrAware fromLotattr, LotattrAware toLotattr, BigDecimal quantity, InventoryChangeActionDto changeAction){
        String m = "";

        if (fromLotattr == null){
            m="库存转移失败.无效的原库存批次属性.";
            return m;
        }
        if (fromLotattr.getMaterialId()==null){
            m="库存转移失败.无效的原库存物料.";
            return m;
        }
        if (toLotattr == null){
            m="库存转移失败.无效的目标库存批次属性.";
            return m;
        }
        if (toLotattr.getMaterialId()==null){
            m="库存转移失败.无效的目标库存物料.";
            return m;
        }
        if (changeAction==null){
            changeAction=new InventoryChangeActionDto();
        }
        if (StringUtils.isNullOrBlank(changeAction.getBatchumber())){
            changeAction.setBatchumber(TextUtils.genBatchNumber());
        }
        if (StringUtils.isNullOrBlank(changeAction.getWorker())){
            changeAction.setWorker(SecurityUtils.getLoginUsername());
        }
        TwaInventoryLotattr flotattr=null;
        TwaInventoryLotnum flotnum=null;
        TwaInventoryLotattr tlotattr=null;
        TwaInventoryLotnum tlotnum=null;
        List<TwaInventoryDetails> storages=null;
        BigDecimal total=BigDecimal.ZERO;
        Set<String> containers=new HashSet<>();
        Long divisionid=null;
        BigDecimal changetoqty=BigDecimal.ZERO;
        BigDecimal openqty=BigDecimal.ZERO;
        BigDecimal remainqty=BigDecimal.ZERO;
        TwaInventoryDetails newstorage=null;
        try{
            flotattr=this.lotattrService.find(fromLotattr);
            if (flotattr==null){
                m="库存转移失败.找不到对应的库存批次.";
                return m;
            }
            flotnum=this.lotnumService.findByLotnoId(flotattr.getId());
            if (flotnum==null){
                m="库存转移失败.找不到对应的库存批次数据.";
                return m;
            }
            storages=this.inventoryService.findByLotnoId(flotattr.getId());
            if ((storages==null) || (storages.size()==0)){
                m="库存转移失败.找不到对应的库存明细数据.";
                return m;
            }
            for (TwaInventoryDetails d:storages){
                if (d==null){
                    continue;
                }
                if ((d.getQtyAllocated()!=null) && (d.getQtyAllocated().compareTo(BigDecimal.ZERO)>0)){
                    m="库存已经分配,不能转移.托盘码:"+d.getContainNumber();
                    return m;
                }
                divisionid=d.getDivisionId();
                total=total.add(d.getQty());
                containers.add(d.getContainNumber());
            }
            //
            /**
            if ((quantity!=null) && (quantity.compareTo(total)!=0)){
                m="库存转移失败.指定的库存转移数量与当前库存总量不一致.转移量:"+quantity.stripTrailingZeros().toPlainString()+",库存总量:"+total.stripTrailingZeros().toPlainString();
                return m;
            }
             **/
            //严格模式
            //涉及托盘处于静态状态(无任务/码盘)等
            if ((changeAction!=null) && ("".equalsIgnoreCase(changeAction.getWorkMode()))){
                //
            }
            //简单处理
            flotattr=this.lotattrService.find(fromLotattr);
            if (flotattr==null){
                m="库存转移失败.找不到对应的库存批次.";
                return m;
            }
            flotnum=this.lotnumService.findByLotnoId(flotattr.getId());
            if (flotnum==null){
                m="库存转移失败.找不到对应的库存批次数据.";
                return m;
            }
            if ((flotnum.getQtyAllocated()!=null) && (flotnum.getQtyAllocated().compareTo(BigDecimal.ZERO)>0)){
                if (total.compareTo(flotnum.getQtyAllocated())>0){
                    m="库存转移失败.变更数量大于原批次已分配锁定数量.原批次已分配数量:"+flotnum.getQtyAllocated().stripTrailingZeros().toPlainString();
                    return m;
                }
            }
            //
            tlotattr=this.lotattrService.find(toLotattr);
            if (tlotattr==null){
                tlotattr=this.lotattrService.create(toLotattr, changeAction.getWorker());
            }
            tlotnum=this.lotnumService.findByLotnoId(tlotattr.getId());
            if (tlotnum==null){
                tlotnum=this.lotnumService.create(tlotattr, divisionid);
            }

            //
            changetoqty=flotnum.getQty();
            changetoqty=changetoqty.subtract(total);
            if (changetoqty.compareTo(BigDecimal.ZERO)<0){
                changetoqty=BigDecimal.ZERO;
            }
            flotnum.setQty(changetoqty);
            /**
            changetoqty=flotnum.getQtyAllocated();
            changetoqty=changetoqty.subtract(total);
            if (changetoqty.compareTo(BigDecimal.ZERO)<0){
                changetoqty=BigDecimal.ZERO;
            }
            flotnum.setQtyAllocated(changetoqty);
            **/

            //
            changetoqty=tlotnum.getQty();
            changetoqty=changetoqty.add(total);
            if (changetoqty.compareTo(BigDecimal.ZERO)<0){
                changetoqty=BigDecimal.ZERO;
            }
            tlotnum.setQty(changetoqty);

            this.lotnumService.save(flotnum);
            this.lotnumService.save(tlotnum);

            remainqty=total;
            for (TwaInventoryDetails td:storages){
                if (td==null){
                    continue;
                }
                if (remainqty.compareTo(BigDecimal.ZERO)<=0){
                    break;
                }
                openqty=td.getQty();
                if ((td.getQtyAllocated()!=null) && (td.getQtyAllocated().compareTo(BigDecimal.ZERO))>0){
                    openqty=openqty.subtract(td.getQtyAllocated());
                }
                if (openqty.compareTo(BigDecimal.ZERO)<=0){
                    continue;
                }
                if (openqty.compareTo(remainqty)>0){
                    openqty=remainqty;
                }
                //
                if (openqty.compareTo(td.getQty())==0){
                    td.setLotnoId(tlotattr.getId());
                    td.setLotnoNumber(tlotattr.getNumber());
                    td.setLotnumId(tlotnum.getId());
                    td.setLastModifiedBy(changeAction.getWorker());
                    td.setLastModifiedDate(new Date());
                    this.inventoryService.save(td);
                }
                //
                if (td.getQty().compareTo(openqty)>0){
                    //
                    changetoqty=td.getQty();
                    changetoqty=changetoqty.subtract(openqty);
                    td.setQty(changetoqty);
                    td.setLastModifiedBy(changeAction.getWorker());
                    td.setLastModifiedDate(new Date());
                    this.inventoryService.save(td);
                    //
                    newstorage= new TwaInventoryDetails();
                    BeanUtils.copyProperties(td, newstorage);
                    td.setId(null);
                    newstorage.setQty(openqty);
                    newstorage.setQtyAllocated(BigDecimal.ZERO);
                    newstorage.setLotnoId(tlotattr.getId());
                    newstorage.setLotnoNumber(tlotattr.getNumber());
                    newstorage.setLotnumId(tlotnum.getId());
                    this.inventoryService.save(newstorage);
                }
                //
                this.transService.transfer(changeAction.getBatchumber(), td, flotattr, tlotattr, tlotnum, openqty, changeAction);

                remainqty=remainqty.subtract(openqty);
                if (remainqty.compareTo(BigDecimal.ZERO)<=0){
                    break;
                }
            }
        }catch (Exception e){
            m="库存转移失败.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    public LocationLineDto currentLocation(String containerNumber){
        LocationLineDto loc=null;
        if (StringUtils.isNullOrBlank(containerNumber)){
            return loc;
        }
        List<TwaInventoryDetails> storages=null;
        try{
            storages=this.inventoryService.findByContainNumber(containerNumber.trim());
            if ((storages==null)||(storages.size()==0)){
                return loc;
            }
            loc=this.locationResolver.lookup(storages.get(0).getLocId());
        }catch (Exception e){
            e.printStackTrace();
        }
        return loc;
    }

    public String currentZone(String containerNumber){
        String zonecode="";
        if (StringUtils.isNullOrBlank(containerNumber)){
            return zonecode;
        }
        List<TwaInventoryDetails> storages=null;
        try{
            storages=this.inventoryService.findByContainNumber(containerNumber.trim());
            if ((storages==null)||(storages.size()==0)){
                return zonecode;
            }
            zonecode=this.locationZone(storages.get(0).getLocId());
        }catch (Exception e){
            e.printStackTrace();
        }
        return zonecode;
    }

    public String locationZone(Long locationId){
        String zonecode="";
        if (locationId==null){
            return zonecode;
        }
        zonecode=this.locationZoneCache.getIfPresent(locationId);
        if (!StringUtils.isNullOrBlank(zonecode)){
            return zonecode;
        }
        LocationLineDto loc= null;
        TwmBasZone zone=null;
        try{
            loc = this.locationResolver.lookup(locationId);
            if (loc!=null){
                zone=this.zoneService.lookup(loc.getZoneId());
                if (zone!=null){
                    zonecode=zone.getCode();
                    this.locationZoneCache.put(locationId, zonecode);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return zonecode;
    }

    public String loadCountData(String divisionCode, List<CountItemDto> items, String worker){
        String m = "";
        if ((items==null) || (items.size()==0)){
            return m;
        }
        Map<Long, TwaInventoryDetails> storagesmap=new HashMap<>();
        List<TwaInventoryDetails> storages=null;
        List<Long> storageids=null;
        Map<String, Long> materials=new HashMap<>();
        Map<String, String> containersmap=new HashMap<>();
        List<String> containers=null;
        TwaDocCoHeader header=null;
        List<TwaDocCoHeader> headers=null;
        TwmBasMaterial mat=null;
        Map<String, String> excontainers=new HashMap<>();
        TwaDocCoDetails line=null;

        Map<Long, Integer> nextlinenum=new HashedMap();
        Integer lineindex=null;
        Long divisionid=null;
        try{
            divisionid = this.divisionService.retrieveOn(divisionCode, XcmgAmConstants.DIVISION_WH101_ID);
            headers=this.dyncdataQueryService.openLastCoDocument(divisionid, XcmgAmConstants.COUNT_TYPE_NORMAL);
            if ((headers==null)||(headers.size()==0)){
                m="找不到盘点单,请先创建[常规]盘点单";
                return m;
            }
            header=headers.get(0);
            //
            for (CountItemDto t:items){
                if (t==null){
                    continue;
                }
                if (!StringUtils.isNullOrBlank(t.getMaterialCode())){
                    t.setMaterialCode(t.getMaterialCode().trim());
                    if (!materials.containsKey(t.getMaterialCode())){
                        mat=this.materialService.lookup(XcmgAmConstants.CUSTOMER_CODE_XCMG_AM, t.getMaterialCode());
                        if (mat!=null){
                            materials.put(mat.getCode(), mat.getId());
                            storages=this.inventoryService.findByMaterialId(mat.getId());
                            if ((storages!=null) && (storages.size()>0)){
                                for (TwaInventoryDetails sd:storages){
                                    if (sd==null){
                                        continue;
                                    }
                                    if (storagesmap.containsKey(sd.getId())){
                                        continue;
                                    }
                                    if ((sd.getQtyAllocated()!=null) && (sd.getQtyAllocated().compareTo(BigDecimal.ZERO)<0)){
                                        excontainers.put(sd.getContainNumber(), CodesConstants.COMMON_FLAG_YES);
                                    }
                                    storagesmap.put(sd.getId(), sd);
                                }
                            }
                        }
                    }
                }
                if (!StringUtils.isNullOrBlank(t.getContainerNumber())){
                    t.setContainerNumber(t.getContainerNumber().trim());
                    if (!containersmap.containsKey(t.getContainerNumber())){
                        containersmap.put(t.getContainerNumber(), CodesConstants.COMMON_FLAG_YES);
                    }
                }
            }
            //
            if ((containersmap!=null)&&(containersmap.size()>0)){
                containers=new ArrayList<>();
                containers.addAll(containersmap.keySet());
                storages=this.dyncdataQueryService.queryInventoryByContainers(header.getDivisionId(), containers);
                if (storages!=null){
                    for (TwaInventoryDetails sd:storages){
                        if (sd==null){
                            continue;
                        }
                        if (storagesmap.containsKey(sd.getId())){
                            continue;
                        }
                        if ((sd.getQtyAllocated()!=null) && (sd.getQtyAllocated().compareTo(BigDecimal.ZERO)<0)){
                            excontainers.put(sd.getContainNumber(), CodesConstants.COMMON_FLAG_YES);
                        }
                        storagesmap.put(sd.getId(), sd);
                    }
                }
            }
            //
            if ((storagesmap==null)||(storagesmap.size()==0)){
                return m;
            }
            storageids=new ArrayList<>();
            for (TwaInventoryDetails sm:storagesmap.values()){
                if (sm==null){
                    continue;
                }
                storageids.add(sm.getId());
            }
            m = this.storageService.generateCount(storageids, worker);

            //SORT
            /**
            for (TwaInventoryDetails sa:storagesall){
                if (sa==null){
                    continue;
                }

                lineindex = nextlinenum.get(header.getId());
                if (lineindex==null){
                    lineindex=this.soDetailsService.maxLineNumber(header.getId());
                    if (lineindex<=0){
                        lineindex=0;
                    }
                    if (lineindex>10){
                        lineindex=lineindex /10;
                    }
                }
                lineindex++;
                line=this.createCoDetails(header, sa, lineindex);
                if (line!=null){
                    this.coDetailsService.save(line);
                    nextlinenum.put(header.getId(), lineindex);
                }
            }
             **/
        }catch (Exception e){
            e.getMessage();
        }
        return m;
    }

    public String setCountStation(Long documentId, List<String> workStations, String worker){
        String m = "";
        if (documentId==null){
            return m;
        }

        if ((workStations==null) || (workStations.size()==0)){
            m="波次必须指定盘点站台.";
            return m;
        }

        if (StringUtils.isNullOrBlank(worker)){
            worker=SecurityUtils.getLoginUsername();
        }
        TwaDocCoHeader header=null;
        String mstation="";
        String pointcodes="";
        LocationLineDto loc=null;
        try{
            header=this.coService.findById(documentId);
            if (header==null){
                m="找不到盘点单,请确认是否已删除.Id:"+String.valueOf(documentId);
                return m;
            }
            if (WmsConstants.CO_STATUS_CHECKOUT.compareTo(header.getStatus())<=0){
                m="盘点已经开始作业,不能再次指定盘点站台.盘点单:"+header.getDocumentNumber();
                return m;
            }
            if (WmsConstants.CO_STATUS_DELIVER.compareTo(header.getStatus())<=0){
                m="盘点结果已经发布,不能再次指定盘点站台.盘点单:"+header.getDocumentNumber();
                return m;
            }
            if (WmsConstants.CO_STATUS_CLOSE.compareTo(header.getStatus())<=0){
                m="盘点结果已经关闭,不能再次指定盘点站台.盘点单:"+header.getDocumentNumber();
                return m;
            }
            if (WmsConstants.CO_STATUS_CANCELL.compareTo(header.getStatus())<=0){
                m="盘点结果已经取消,不能再次指定盘点站台.盘点单:"+header.getDocumentNumber();
                return m;
            }
            for (String d:workStations){
                if (StringUtils.isNullOrBlank(d)){
                    continue;
                }
                loc=this.locationResolver.lookup(header.getId(), d.trim());
                if (loc==null){
                    m="找不到拣货站台,请确认是否误删除.站台号:"+d;
                    return m;
                }
                if (StringUtils.isNullOrBlank(mstation)){
                    mstation=loc.getLocationCode();
                }
                if (!StringUtils.isNullOrBlank(pointcodes)){
                    pointcodes=pointcodes+";";
                }
                pointcodes=pointcodes+this.wcsCustomWorkService.takePointcode(loc);
            }
            if (StringUtils.isNullOrBlank(mstation)){
                m="未找到有效的拣货站台.";
                return m;
            }
            //
            header.setDockNumber(mstation);
            header.setPlanLoadPlace(pointcodes);
            header.setLastModifiedBy(worker);
            header.setLastModifiedDate(new Date());
            this.coService.save(header);
        }catch (Exception e){
            m="设置盘点站台失败.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    public int coDetailsContainerCount(Long documentId){
        int count=0;
        if (documentId==null){
            return count;
        }
        List<TwaDocCoDetails> lines=null;
        Set<String> conts=new HashSet<String>();
        try{
            lines=this.coDetailsService.findByDocumentId(documentId);
            if ((lines==null)||(lines.size()==0)){
                return count;
            }
            for (TwaDocCoDetails d:lines){
                if (d==null){
                    continue;
                }
                if (StringUtils.isNullOrBlank(d.getContainNumber())){
                    continue;
                }
                conts.add(d.getContainNumber());
            }
            count=conts.size();
        }catch (Exception e){
            e.printStackTrace();
        }

        return count;
    }

    public String moveout(List<Long> storageIds, List<String> plantoLocations, TaskActionDto actionDto){
        String m = "";

        return m;
    }

    //
    public String deliverCount(Long documentId, TaskActionDto actionDto){
        String m="";
        if (documentId==null){
            m="document id is null";
            return m;
        }
        if (actionDto==null){
            actionDto=new TaskActionDto();
        }
        if (StringUtils.isNullOrBlank(actionDto.getWorker())){
            actionDto.setWorker(SecurityUtils.getLoginUsername());
        }
        TwaDocCoHeader header=null;
        List<TwaDocCoDetails> lines=null;
        Date now=new Date();
        TwaInventoryDetails storage=null;
        BigDecimal qtydiff=null;
        BigDecimal qtyusable=null;
        String batchnum="";
        try{
            header=this.coService.findById(documentId);
            if (WmsConstants.CO_STATUS_CLOSE.equalsIgnoreCase(header.getStatus())){
                m="盘点单已经关闭,不能再次发布.单号:"+header.getDocumentNumber();
                return m;
            }
            if (WmsConstants.CO_STATUS_CLOSE.equalsIgnoreCase(header.getStatus())){
                m="盘点单已经取消,不能再次发布.单号:"+header.getDocumentNumber();
                return m;
            }
            if (WmsConstants.CO_STATUS_DELIVER.equalsIgnoreCase(header.getStatus())){
                m="盘点单已经发布,不能重复发布.单号:"+header.getDocumentNumber();
                return m;
            }
            batchnum=TextUtils.genBatchNumber();
            lines=this.coDetailsService.findByDocumentId(header.getId());
            if ((lines!=null) && (lines.size()>0)){
                for (TwaDocCoDetails line:lines){
                    if (line==null){
                        continue;
                    }
                    m=this.deliverCount(batchnum, line, actionDto.getWorker(), false);
                    if (!StringUtils.isNullOrBlank(m)){
                        return m;
                    }
                    /**
                    if (WmsConstants.CO_STATUS_CLOSE.equalsIgnoreCase(line.getLineStatus())){
                        continue;
                    }
                    if (WmsConstants.CO_STATUS_CANCELL.equalsIgnoreCase(line.getLineStatus())){
                        continue;
                    }
                    if (WmsConstants.CO_STATUS_DELIVER.equalsIgnoreCase(line.getLineStatus())){
                        //m="盘点明细已经发布,不能重复发布.单号:"+header.getDocumentNumber();
                        return m;
                    }
                    storage=this.inventoryService.findById(line.getStorageId());
                    if (storage==null){
                        m="自动调账失败.库存已经发生变化,找不到库存数据.行号:"+line.getLineNumber()+",库存ID:"+String.valueOf(line.getStorageId());
                        return m;
                    }
                    if ((storage.getQtyAllocated()!=null)&&(storage.getQtyAllocated().compareTo(BigDecimal.ZERO)>0)){
                        m="自动调账失败.相关库存已经发生变化，生成了拣货数据,请在拣货后进行调账.行号:"+line.getLineNumber()+",库存托盘:"+storage.getContainNumber();
                        return m;
                    }
                    qtydiff=BigDecimal.ZERO;
                    if ((WmsConstants.CO_STATUS_COUNT.equalsIgnoreCase(line.getLineStatus()))
                            && (line.getQtyCount()!=null)){
                        if (line.getQtyOrdered()!=null){
                            qtydiff=line.getQtyOrdered().subtract(line.getQtyCount());
                        }
                    }
                    if ((WmsConstants.CO_STATUS_CHECK.equalsIgnoreCase(line.getLineStatus()))
                            && (line.getQtyChecked()!=null)){
                        if (line.getQtyOrdered()!=null){
                            qtydiff=line.getQtyOrdered().subtract(line.getQtyChecked());
                        }
                    }
                    if (qtydiff.compareTo(BigDecimal.ZERO)>0){
                        if (qtydiff.compareTo(storage.getQty())>0){
                            m="自动调账失败.相关库存已经发生变化，盘点差异数量大于当前库存数量.行号:"+line.getLineNumber()+",库存托盘:"+storage.getContainNumber();
                            return m;
                        }
                        if ((storage.getQtyAllocated()!=null)&&(storage.getQtyAllocated().compareTo(BigDecimal.ZERO)>0)){
                            qtyusable=storage.getQty().subtract(storage.getQtyAllocated());
                            if (qtydiff.compareTo(qtyusable)>0){
                                m="自动调账失败.相关库存已经发生变化，盘点差异数量大于当前可用库存数量.行号:"+line.getLineNumber()+",库存托盘:"+storage.getContainNumber();
                                return m;
                            }
                        }
                    }
                    if (!StringUtils.isNullOrBlank(line.getContainNumber())){
                        if (!line.getContainNumber().equalsIgnoreCase(storage.getContainNumber())){
                            m="自动调账失败.相关库存已经发生变化，库存托盘非盘点托盘.行号:"+line.getLineNumber()+",盘点托盘:"+line.getContainNumber()+",库存托盘:"+storage.getContainNumber();
                            return m;
                        }
                    }
                    //调整库存
                    if (qtydiff.compareTo(BigDecimal.ZERO)!=0){
                        m=this.adjustQuantity(batchnum, storage, qtydiff.negate(), actionDto.getWorker());
                        if (!StringUtils.isNullOrBlank(m)){
                            return m;
                        }
                    }
                    if ((line.getQtyCheckin()==null) || (line.getQtyCheckin().compareTo(line.getQtyOrdered())<0)){
                        line.setQtyCheckin(line.getQtyOrdered());
                    }
                    if ((line.getQtyCheckinEach()==null) || (line.getQtyCheckinEach().compareTo(line.getQtyOrderedEach())<0)){
                        line.setQtyCheckinEach(line.getQtyOrderedEach());
                    }
                    if ((line.getLineStatus().compareTo(WmsConstants.CO_STATUS_CREATE)>=0)
                            && ((line.getLineStatus().compareTo(WmsConstants.CO_STATUS_COUNT)<0))){
                        line.setQtyCount(line.getQtyOrdered());
                        line.setQtyCountEach(line.getQtyOrderedEach());
                    }
                    if (line.getCheckTime()==null){
                        line.setCountTime(now);
                    }
                    if (StringUtils.isNullOrBlank(line.getCountBy())){
                        line.setCountBy(actionDto.getWorker());
                    }
                    //if (WmsConstants.COUNT_DELIVER_MODE_AUTO.equalsIgnoreCase(workMode)){
                    //}
                    line.setLineStatus(WmsConstants.CO_STATUS_DELIVER);
                    line.setLastModifiedBy(actionDto.getWorker());
                    line.setLastModifiedDate(now);
                    this.coDetailsService.save(line);
                     **/
                }
            }
            header.setStatus(WmsConstants.CO_STATUS_DELIVER);
            header.setNotes(actionDto.getNotes());
            header.setLastModifiedBy(actionDto.getWorker());
            header.setLastModifiedDate(now);
            this.coService.save(header);
        }catch (Exception e){
            m="发布盘点单异常.错误:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    private String deliverCount(String batchNumber, TwaDocCoDetails line, String worker, boolean checkError){
        String m = "";
        if (line==null){
            if (checkError){
                m="盘点单明细行为空";
            }
            return m;
        }
        if (WmsConstants.CO_STATUS_CLOSE.equalsIgnoreCase(line.getLineStatus())){
            if (checkError){
                m="盘点单明细行已经关闭";
            }
            return m;
        }
        if (WmsConstants.CO_STATUS_CANCELL.equalsIgnoreCase(line.getLineStatus())){
            if (checkError){
                m="盘点单明细行已经取消";
            }
            return m;
        }
        if (WmsConstants.CO_STATUS_DELIVER.equalsIgnoreCase(line.getLineStatus())){
            if (checkError){
                m="盘点明细已经发布,不能重复发布.行号:"+line.getLineNumber();
            }
            return m;
        }
        TwaInventoryDetails storage=null;
        BigDecimal qtydiff=BigDecimal.ZERO;
        BigDecimal qtyusable=BigDecimal.ZERO;
        try{
            storage=this.inventoryService.findById(line.getStorageId());
            if (storage==null){
                m="自动调账失败.库存已经发生变化,找不到库存数据.行号:"+line.getLineNumber()+",库存ID:"+String.valueOf(line.getStorageId());
                return m;
            }
            if ((storage.getQtyAllocated()!=null)&&(storage.getQtyAllocated().compareTo(BigDecimal.ZERO)>0)){
                m="自动调账失败.相关库存已经发生变化，生成了拣货数据,请在拣货后进行调账.行号:"+line.getLineNumber()+",库存托盘:"+storage.getContainNumber();
                return m;
            }
            qtydiff=BigDecimal.ZERO;
            if ((WmsConstants.CO_STATUS_COUNT.equalsIgnoreCase(line.getLineStatus())) && (line.getQtyCount()!=null)){
                if (line.getQtyOrdered()!=null){
                    qtydiff=line.getQtyOrdered().subtract(line.getQtyCount());
                }
            }
            if ((WmsConstants.CO_STATUS_CHECK.equalsIgnoreCase(line.getLineStatus()))  && (line.getQtyChecked()!=null)){
                if (line.getQtyOrdered()!=null){
                    qtydiff=line.getQtyOrdered().subtract(line.getQtyChecked());
                }
            }
            if (qtydiff.compareTo(BigDecimal.ZERO)>0){
                if (qtydiff.compareTo(storage.getQty())>0){
                    m="自动调账失败.相关库存已经发生变化，盘点差异数量大于当前库存数量.行号:"+line.getLineNumber()+",库存托盘:"+storage.getContainNumber();
                    return m;
                }
                if ((storage.getQtyAllocated()!=null)&&(storage.getQtyAllocated().compareTo(BigDecimal.ZERO)>0)){
                    qtyusable=storage.getQty().subtract(storage.getQtyAllocated());
                    if (qtydiff.compareTo(qtyusable)>0){
                        m="自动调账失败.相关库存已经发生变化，盘点差异数量大于当前可用库存数量.行号:"+line.getLineNumber()+",库存托盘:"+storage.getContainNumber();
                        return m;
                    }
                }
            }
            if (!StringUtils.isNullOrBlank(line.getContainNumber())){
                if (!line.getContainNumber().equalsIgnoreCase(storage.getContainNumber())){
                    m="自动调账失败.相关库存已经发生变化，库存托盘非盘点托盘.行号:"+line.getLineNumber()+",盘点托盘:"+line.getContainNumber()+",库存托盘:"+storage.getContainNumber();
                    return m;
                }
            }
            //调整库存
            if (qtydiff.compareTo(BigDecimal.ZERO)!=0){
                m=this.adjustQuantity(batchNumber, storage, qtydiff.negate(), worker);
                if (!StringUtils.isNullOrBlank(m)){
                    return m;
                }
            }
            if ((line.getQtyCheckin()==null) || (line.getQtyCheckin().compareTo(line.getQtyOrdered())<0)){
                line.setQtyCheckin(line.getQtyOrdered());
            }
            if ((line.getQtyCheckinEach()==null) || (line.getQtyCheckinEach().compareTo(line.getQtyOrderedEach())<0)){
                line.setQtyCheckinEach(line.getQtyOrderedEach());
            }
            if ((line.getLineStatus().compareTo(WmsConstants.CO_STATUS_CREATE)>=0)
                    && ((line.getLineStatus().compareTo(WmsConstants.CO_STATUS_COUNT)<0))){
                line.setQtyCount(line.getQtyOrdered());
                line.setQtyCountEach(line.getQtyOrderedEach());
            }
            if (line.getCheckTime()==null){
                line.setCountTime(new Date());
            }
            if (StringUtils.isNullOrBlank(line.getCountBy())){
                line.setCountBy(worker);
            }
            //if (WmsConstants.COUNT_DELIVER_MODE_AUTO.equalsIgnoreCase(workMode)){
            //}
            line.setLineStatus(WmsConstants.CO_STATUS_DELIVER);
            line.setLastModifiedBy(worker);
            line.setLastModifiedDate(new Date());
            this.coDetailsService.save(line);

        }catch (Exception e){
            m="盘点明细行调账失败.错误:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    private String adjustQuantity(String batchNumber, TwaInventoryDetails storage, BigDecimal changeQuantity, String worker){
        String m = "";
        if (storage==null){
            return m;
        }
        // create object
        try {
            InventoryChangeActionDto changeActionDto=new InventoryChangeActionDto();
            changeActionDto.setBatchumber(batchNumber);
            changeActionDto.setOperationType(WmsConstants.INVENTORY_ACTION_ADJUST);
            changeActionDto.setWorker(SecurityUtils.getLoginUsername());
            changeActionDto.setWorkTime(new Date());
            m = this.storageService.adjust(batchNumber, storage, changeQuantity, changeActionDto);
            log.info("COUNT-DELIVER auto ajust quantity//{batchnum:{}, storageid:{}, containnum:{}, tracenum:{}, qty:{}, allocateqty:{}, changeqty:{}, worker:{}, status:{}}",
                    batchNumber, storage.getId(), storage.getContainNumber(), storage.getTraceNumber(), storage.getQty(), storage.getQtyAllocated(), changeQuantity, worker, m);
        } catch (Exception e)  {
            log.error("库存调整失败:异常", e);
        }
        return m;
    }


/**==================================================================================================================**/
// ---- CUSTOM/II/COMMON
/**==================================================================================================================**/

    public TaskActionDto defDivisionWork(TaskActionDto actionDto){
        if (actionDto==null){
            actionDto=new TaskActionDto();
        }
        if ((actionDto!=null) && (StringUtils.isNullOrBlank(actionDto.getDivisionCode()))){
            actionDto.setDivisionId(XcmgAmConstants.DIVISION_WH101_ID);
            actionDto.setDivisionCode(XcmgAmConstants.DIVISION_WH101_CODE);
        }
        if ((actionDto.getDivisionId()==null) && (!StringUtils.isNullOrBlank(actionDto.getDivisionCode()))){
            actionDto.setDivisionId(this.divisionService.retrieve(actionDto.getDivisionCode()));
        }
        if ((actionDto.getDivisionId()!=null) && (StringUtils.isNullOrBlank(actionDto.getDivisionCode()))){
            actionDto.setDivisionCode(this.divisionService.retrieve(actionDto.getDivisionId()));
        }
        return actionDto;
    }

    public TaskActionDto workAction(TaskActionDto actionDto){
        TaskActionDto workaction=this.defDivisionWork(actionDto);
        if (StringUtils.isNullOrBlank(actionDto.getWorker())){
            actionDto.setWorker(SecurityUtils.getLoginUsername());
        }
        return workaction;
    }

    public boolean closed(TwtActTaskList task){
        if (task==null){
            return true;
        }
        if (WmsConstants.TASK_STATUS_CLOSE.equalsIgnoreCase(task.getStatus())){
            return true;
        }
        if (WmsConstants.TASK_STATUS_CANCEL.equalsIgnoreCase(task.getStatus())){
            return true;
        }
        return false;
    }

    public boolean closed(TwtActAllocationList allocation){
        if (allocation==null){
            return true;
        }
        if (WmsConstants.SO_STATUS_SHIP.equalsIgnoreCase(allocation.getStatus())){
            return true;
        }
        if (WmsConstants.SO_STATUS_CLOSE.equalsIgnoreCase(allocation.getStatus())){
            return true;
        }
        if (WmsConstants.SO_STATUS_CANCELL.equalsIgnoreCase(allocation.getStatus())){
            return true;
        }
        return false;
    }

    public boolean closed(TwaDocSoHeader header){
        if (header==null){
            return true;
        }
        if (WmsConstants.SO_STATUS_CLOSE.equalsIgnoreCase(header.getStatus())){
            return true;

        }
        if (WmsConstants.SO_STATUS_CANCELL.equalsIgnoreCase(header.getStatus())){
            return true;
        }
        return false;
    }

    public String checkOrder(List<TaskOrderDto> tasks, Map<String, TwmBasMaterial> materials){
        String m="";
        if ((tasks==null)||(tasks.size()==0)){
            m="订单数据位空.";
            return m;
        }
        String customercode=XcmgAmConstants.CUSTOMER_CODE_XCMG_AM;
        TwmBasMaterial mat=null;
        List<TwaDocSoDetails> lines=null;
        try{
            if (!StringUtils.isNullOrBlank(tasks.get(0).getOwner())){
                customercode=tasks.get(0).getOwner().trim();
            }
            //
            for (TaskOrderDto t:tasks){
                if (t==null){
                    continue;
                }
                mat=this.materialService.lookup(customercode, t.getMCode().trim());
                if (mat==null){
                    //mat=this.loadMaterial(t);
                    if (mat==null){
                        m="自动生成物料主数据出错.物料编码:"+t.getMCode();
                        return m;
                    }
                }
                if (materials!=null){
                    materials.put(t.getMCode(), mat);
                }
                lines=this.dyncdataQueryService.xwmsSoTaskOf(t.getTaskCode());
                if ((lines!=null) && (lines.size()>0)){
                    m="任务已经导入.任务号:"+t.getTaskCode();
                    return m;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return m;
    }

    public void populate(ShipHeaderDto header, List<WaveShipLineDto> lines, List<TwtActAllocationList> details){
        if ((details==null) || (details.size()==0)){
            header.setQtysum("0/0");
            return;
        }
        //fill
        int count=0;
        BigDecimal sum=BigDecimal.ZERO;
        WaveShipLineDto line=null;
        Map<Long,TwmBasMaterial> materials=new HashMap<Long,TwmBasMaterial>();
        Map<Long,TwaDocWaveHeader> wheaders=new HashMap<Long,TwaDocWaveHeader>();
        TwaDocWaveHeader wheader=null;
        String czonecode=this.currentZone(details.get(0).getFromContainNumber());
        String pzonecode="";
        for(TwtActAllocationList d:details){
            if (!this.checkAllocate(d)){
                continue;
            }
            wheader=wheaders.get(d.getWaveId());
            if (wheader==null){
                wheader=this.waveService.findById(d.getWaveId());
                if (wheader!=null){
                    wheaders.put(wheader.getId(),wheader);
                    header.setConsigneecode(wheader.getConsigneeCode());
                    header.setConsigneename(wheader.getConsigneeName());
                    header.setPlantoplace(wheader.getPickLocationCode());
                }
            }
            line=translateTo(d,materials,wheaders);
            if (line!=null){
                if (this.livePickMode()){
                    pzonecode=this.locationZone(d.getToLocId());
                    if (XcmgAmConstants.onlinePickZoneMap.containsKey(pzonecode)){
                        if (pzonecode.equalsIgnoreCase(czonecode)){
                            line.setZoneprior(XcmgAmConstants.PRIOR_HIGH);
                        }
                    }
                }
                lines.add(line);
                count++;
                sum= MathUtils.add(sum, d.getQtyEach());
            }
            if(count==1){
                header.setCreateby(d.getCreatedBy());
                header.setCreatetime(DateUtils.format(d.getCreatedDate(),DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS));
                header.setContainnumber(d.getFromContainNumber());
            }
        }
        String qtysum=String.valueOf(count)+"/"+MathUtils.getQuantityString(sum);
        header.setQtysum(qtysum);

        if ((lines!=null) && (lines.size()>0)){
            Collections.sort(lines , new Comparator<WaveShipLineDto>(){
                public int compare(WaveShipLineDto a , WaveShipLineDto b){
                    int seq=a.getZoneprior().compareTo(b.getZoneprior());
                    if (seq!=0){
                        return seq;
                    }
                    return a.getId().compareTo(b.getId());
                }
            });
        }
        int index=0;
        String total=String.valueOf(lines.size());
        for (WaveShipLineDto d:lines){
            if (d==null){
                continue;
            }
            index++;
            d.setSplitinfo(String.valueOf(index)+"/"+total);
        }
    }

    public void populate(CountTaskHeaderDto header, List<CounWorkLineDto> lines, List<TwtActTaskList> tasks){
        if ((tasks==null) || (tasks.size()==0)){
            header.setQtysum("0/0");
            return;
        }
        //fill
        int count=0;
        BigDecimal sum=BigDecimal.ZERO;
        CounWorkLineDto line=null;
        TwaInventoryLotattr lotattr=null;
        Map<Long,TwmBasMaterial> materials=new HashMap<Long,TwmBasMaterial>();
        Map<Long,TwaDocCoHeader> cheaders=new HashMap<Long,TwaDocCoHeader>();
        int index=0;
        int total= tasks.size();
        for(TwtActTaskList t:tasks){
            index++;
            if (t==null){
                continue;
            }
            line=translateTo(t,materials,cheaders);
            if (line!=null){
                lotattr=this.lotattrService.findById(t.getFromLotnoId());
                if (lotattr!=null){
                    line.setLotattr05(lotattr.getLotattr05());
                    line.setLotattr06(lotattr.getLotattr06());
                    line.setLotattr07(lotattr.getLotattr07());
                }
                lines.add(line);
                count++;
                sum= MathUtils.add(sum, t.getFromQty());
            }
            if(count==1){
                header.setCreateby(t.getCreatedBy());
                header.setCreatetime(DateUtils.format(t.getCreatedDate(),DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS));
                //header.setContainnumber(t.getFromContainNumber());
            }

            line.setWorkseqnum(String.valueOf(index)+"/"+String.valueOf(total));
        }
        String qtysum=String.valueOf(count)+"/"+MathUtils.getQuantityString(sum);
        header.setQtysum(qtysum);

        if ((lines!=null) && (lines.size()>0)){
            Collections.sort(lines , new Comparator<CountTaskLineDto>(){
                public int compare(CountTaskLineDto a , CountTaskLineDto b){
                    return a.getId().compareTo(b.getId());
                }
            });
        }
    }

    public String changeTaskStatus(List<TwtActTaskList> tasks, String statusCode, String statusText, String worker){
        String m = "";
        if ((tasks==null)||(tasks.size()==0)){
            return m;
        }
        if (StringUtils.isNullOrBlank(statusCode)){
            m="task's new status is blank";
            return m;
        }

        if (StringUtils.isNullOrBlank(worker)){
            worker= CodesConstants.SYSTEM_USER_WCS;
        }
        for (TwtActTaskList t:tasks){
            if (this.closed(t)){
                continue;
            }
            try{
                t.setStatus(statusCode.trim());
                t.setErrorMessages(statusText);
                t.setLastModifiedDate(new Date());
                t.setLastModifiedBy(worker);
                this.taskService.save(t);
            }catch (Exception e){
                m="更新任务出错.任务号:"+t.getNumber()+",错误信息:"+e.getMessage();
                e.printStackTrace();
            }
        }
        return m;
    }

    public String changeReleaseTaskStatus(List<TwtActTaskList> tasks, String statusCode, String releaseStatus, String statusText, String worker){
        String m = "";
        if ((tasks==null)||(tasks.size()==0)){
            return m;
        }
        if (StringUtils.isNullOrBlank(statusCode)){
            m="task's new status is blank";
            return m;
        }

        if (StringUtils.isNullOrBlank(worker)){
            worker= CodesConstants.SYSTEM_USER_WCS;
        }
        if (StringUtils.isNullOrBlank(releaseStatus)){
            releaseStatus=CodesConstants.COMMON_RELEASE_STATUS_WORKING;
        }
        for (TwtActTaskList t:tasks){
            if (this.closed(t)){
                continue;
            }
            try{
                t.setStatus(statusCode.trim());
                t.setReleaseStatus(releaseStatus);
                t.setErrorMessages(statusText);
                t.setLastModifiedDate(new Date());
                t.setLastModifiedBy(worker);
                this.taskService.save(t);
            }catch (Exception e){
                m="更新任务出错.任务号:"+t.getNumber()+",错误信息:"+e.getMessage();
                e.printStackTrace();
            }
        }
        return m;
    }

    public String containerFullMove(String containNumber, LocationLineDto location, String worker){
        String m = "";
        if (StringUtils.isNullOrBlank(containNumber)){
            m="container number is blank.";
            return m;
        }
        if (location==null){
            m="location is null.";
            return m;
        }
        if (StringUtils.isNullOrBlank(worker)){
            worker= CodesConstants.SYSTEM_USER_SCS;
        }
        String batchNumber=null;
        InventoryChangeActionDto actionDto=null;
        try{
            batchNumber=TextUtils.genBatchNumber();
            actionDto=new InventoryChangeActionDto();
            actionDto.setWorker(worker);
            actionDto.setWorkMode(WmsConstants.PICK_TASK_FIN_MODE_MOVE_PICK);
            actionDto.setChangeMode(WmsConstants.PICK_TASK_FIN_MODE_FULL_MOVE_PICK);
            m=this.storageService.move(batchNumber,containNumber,location.getLocationCode(),actionDto);
        }catch (Exception e){
            m="move container error:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    public String acceptEpal(String containerNumber, String divisionCode, String containerType, String locationCode, String workMode){

        String m="";
        if (StringUtils.isNullOrBlank(containerNumber)){
            m="请扫描托盘码.";
            return m;
        }
        containerNumber=containerNumber.trim();
        Long divisionid= XcmgAmConstants.DIVISION_WH101_ID;
        if (!StringUtils.isNullOrBlank(divisionCode)){
            divisionid=this.divisionService.retrieve(divisionCode.trim());
        }
        List<TwaInventoryDetails> storages=null;
        List<TwtActTaskList> tasks=null;
        List<TwtActPalletizeList> pals=null;
        try{
            storages=this.inventoryService.findByContainNumber(containerNumber);
            if ((storages!=null) && (storages.size()>0)) {
                for (TwaInventoryDetails d : storages) {
                    if (d == null) {
                        continue;
                    }
                    if (!d.getMaterialId().equals(XcmgAmConstants.MATERIAL_ID_EPAL)) {
                        m = "托盘已经放有物料,非空托,请确认是否托盘码重复.托盘码:" + containerNumber;
                        return m;
                    }
                    if (d.getMaterialId().equals(XcmgAmConstants.MATERIAL_ID_EPAL)) {
                        return m;
                    }
                }
                return m;
            }
            tasks=this.taskService.queryWorkingTasks("", containerNumber);
            if ((tasks!=null)&&(tasks.size()>0)){
                m="托盘尚有任务执行,不能空盘上架.任务号:"+tasks.get(0).getNumber();
                return m;
            }
            pals=this.palletizeService.findByContainNumber(containerNumber);
            if ((pals!=null)&&(pals.size()>0)){
                m="托盘已经码盘,不能空盘上架.请确认是否托盘码重复.托盘码:"+containerNumber;
                return m;
            }
            if (StringUtils.isNullOrBlank(containerType)){
                if (containerNumber.startsWith(XcmgAmConstants.CONTAINER_TYPE_PALLET)){
                    containerType=XcmgAmConstants.CONTAINER_TYPE_PALLET;
                }
                if (containerNumber.startsWith(XcmgAmConstants.CONTAINER_TYPE_TOTE)){
                    containerType=XcmgAmConstants.CONTAINER_TYPE_TOTE;
                }
            }
            if (StringUtils.isNullOrBlank(locationCode)){
                locationCode=XcmgAmConstants.LOCATION_CODE_PA0101;
            }
            m=this.storageService.addEpalInventory(divisionid, XcmgAmConstants.CUSTOMER_CODE_XCMG_AM, WmsConstants.MATERIAL_CODE_EMPTY_PALLET, containerNumber, containerType, BigDecimal.ONE, locationCode, "");
        }catch (Exception e){
            m="clean epal error.//error:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    public String releaseEpal(String containnum){
        String m="";
        if (StringUtils.isNullOrBlank(containnum)){
            return m;
        }
        containnum=containnum.trim();
        List<TwaInventoryDetails> storages=null;
        List<TwtActTaskList> tasks=null;
        List<TwtActPalletizeList> pals=null;
        try{
            storages=this.inventoryService.findByContainNumber(containnum);
            if ((storages!=null) && (storages.size()>0)) {
                for (TwaInventoryDetails d : storages) {
                    if (d == null) {
                        continue;
                    }
                    if (!d.getMaterialId().equals(XcmgAmConstants.MATERIAL_ID_EPAL)) {
                        m = "托盘放有物料,非空托,请确认是否托盘码重复.托盘码:" + containnum;
                        return m;
                    }
                }
            }
            tasks=this.taskService.queryWorkingTasks("", containnum);
            if ((tasks!=null)&&(tasks.size()>0)){
                m="托盘尚有任务执行,不能释放.任务号:"+tasks.get(0).getNumber();
                return m;
            }
            pals=this.palletizeService.findByContainNumber(containnum);
            if ((pals!=null)&&(pals.size()>0)){
                m="托盘已经码盘,不能释放.请确认是否托盘码重复.托盘码:"+containnum;
                return m;
            }
            if ((storages!=null) && (storages.size()>0)) {
                for (TwaInventoryDetails d : storages) {
                    if (d == null) {
                        continue;
                    }
                    d.setQty(BigDecimal.ZERO);
                    d.setQtyAllocated(BigDecimal.ZERO);
                    d.setLastModifiedBy(CodesConstants.SYSTEM_RCS);
                    d.setLastModifiedDate(new Date());
                    this.inventoryService.save(d);
                }
            }
        }catch (Exception e){
            m="clean epal error.//error:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    public String replenishEpal(Long divisionId, String locationCode, String containerType, int count){
        String m = "";
        String taskoptions=XcmgAmConstants.wh101EpalReplStationOptions;
        if (XcmgAmConstants.DIVISION_WH101_ID.equals(divisionId)) {
            if (StringUtils.isNullOrBlank(locationCode)){
                locationCode=XcmgAmConstants.LOCATION_CODE_PA1054;
            }
        }
        if (count<=0){
            count=1;
        }
        if (StringUtils.isNullOrBlank(containerType)){
            containerType=XcmgAmConstants.CONTAINER_TYPE_TOTE;
        }
        PutawayActionDto paActionDto = null;
        List<String> containers=null;
        List<TwtActTaskList> tasks=null;
        Map<String, String> checkmap=new HashedMap();
        String batchnum=TextUtils.genBatchNumber();
        TwmBasLocation toloc=null;
        TaskActionDto taskActionDto=new TaskActionDto();
        int maxsize=0;
        int curcount=0;
        int total=0;
        try{
            //toloc=this.locationResolver.find(divisionId, locationCode);
            toloc=this.locationService.findByCode(divisionId, locationCode);
            if (toloc==null){
                m="无效的空托呼叫库位.编码:"+locationCode;
                return m;
            }
            if (WmsConstants.LOCATION_STATUS_LOCKED.equalsIgnoreCase(toloc.getStatus())){
                m="库位暂时锁定,不生成补空托盘任务.库位编码:"+locationCode;
                return m;
            }
            maxsize = XcmgAmConstants.epalReplBufSizes.get(divisionId);
            if (maxsize<=0){
                maxsize=3;
            }
            if (maxsize>count){
                maxsize=count;
            }
            //
            tasks=this.taskService.queryWorkingTasks("","");
            if ((tasks!=null) && (tasks.size()>0)){
                for (TwtActTaskList at:tasks){
                    if (at==null){
                        continue;
                    }
                    if (!at.getDivisionId().equals(divisionId)){
                        continue;
                    }
                    if (!at.getMaterialId().equals(XcmgAmConstants.MATERIAL_ID_EPAL)){
                        continue;
                    }
                    if (toloc.getLocationId().equals(at.getId())){
                        curcount=curcount+1;
                    }else {
                        if ((at.getPlantoLocId()!=null) && (at.getPlantoLocId().equals(toloc.getLocationId()))){
                            curcount=curcount+1;
                        }
                    }
                    //full working
                    if (curcount>=maxsize){
                        return m;
                    }
                }
            }
            //
            paActionDto = new PutawayActionDto();
            paActionDto.setCheckDivisionId(divisionId);
            containers=this.takeEpalStorages(paActionDto, containerType);
            if ((containers==null)||(containers.size()==0)){
                m="找不到有效的空托库存.";
                return m;
            }
            total=maxsize-curcount;
            if (total>count){
                total=count;
            }
            for (String c:containers){
                if (total<=0){
                    break;
                }
                if (StringUtils.isNullOrBlank(c)){
                    continue;
                }
                if (checkmap.containsKey(c)){
                    continue;
                }
                checkmap.put(c, CodesConstants.COMMON_FLAG_YES);
                this.storageService.moveTask(batchnum, c, toloc, taskActionDto);
                //
                tasks=this.taskService.queryWorkingTasks("", c);
                if ((tasks==null)||(tasks.size()==0)){
                    continue;
                }
                for (TwtActTaskList t:tasks){
                    if (t==null){
                        continue;
                    }
                    t.setTaskFeature(taskoptions);
                    this.taskService.save(t);
                }
                //
                m = this.sendWasTaskToWcs(tasks, batchnum, XcmgAmConstants.WCS_EPAL_REPL_USER);
                total=total-1;
            }
            //
        }catch (Exception e){
            m="空托补充报错.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    private List<String> takeEpalStorages(PutawayActionDto actionDto, String containerType){

        List<String> containers=null;
        StringBuffer sql=new StringBuffer();
        String container=null;
        try{
            sql.append("select t1.contain_number ");
            sql.append("from vwa_inv_epal_list t1 ");
            sql.append("where 1=1 ");
            if (!StringUtils.isNullOrBlank(containerType)){
                sql.append("  and t1.container_type= '").append(containerType.trim()).append("' ");
            }
            //
            sql.append(this.fullCheck(actionDto));
            //
            sql.append("order by t1.pa_seq_code desc ");

            Query query=this.entityManager.createNativeQuery(sql.toString());
            List<String> cs=query.getResultList();
            if ((cs==null)||(cs.size()==0)){
                return containers;
            }
            containers=new ArrayList<>();
            for (Object o:cs){
                if (o==null){
                    continue;
                }
                container=null;
                /**
                if (o instanceof Long){
                    idval=(Long)o;
                }
                if (o instanceof BigInteger){
                    idval=((BigInteger)o).longValue();
                }
                if (o instanceof BigDecimal){
                    idval=((BigDecimal)o).longValue();
                }
                 **/
                if (o instanceof String){
                    container=((String)o);
                }

                if (container!=null){
                    containers.add(container);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return containers;
    }

    public LocationLineDto takeSrmpickLocation(Long fromlocid){
        LocationLineDto nextloc=null;
        if (fromlocid==null){
            return nextloc;
        }
        nextloc=this.srmPickLocationMap.get(fromlocid);
        if (nextloc!=null){
            return nextloc;
        }
        LocationLineDto fmloc=this.locationResolver.lookup(fromlocid);
        if ((fmloc!=null) && (fmloc.getFlowtoLocId()!=null)){
            if (fmloc.getFlowtoLocId().equals(fmloc.getLocationId())){
                nextloc=fmloc;
            }else {
                nextloc=this.locationResolver.lookup(fmloc.getFlowtoLocId());
            }
        }
        return nextloc;
    }

    private void defValue(PalletizeChangeData palletizeData, TaskActionDto actionDto) {
        if (palletizeData!=null){
            if (StringUtils.isNullOrBlank(palletizeData.getCustomercode())){
                palletizeData.setCustomercode(XcmgAmConstants.CUSTOMER_CODE_XCMG_AM);
            }
            if (StringUtils.isNullOrBlank(palletizeData.getDivisioncode())){
                palletizeData.setDivisioncode(XcmgAmConstants.DIVISION_WH101_CODE);
            }
            if (StringUtils.isNullOrBlank(palletizeData.getLotattr06())){
                palletizeData.setLotattr06(CodesConstants.COMMON_WILDCARD);
            }
            if (StringUtils.isNullOrBlank(palletizeData.getLotattr07())){
                palletizeData.setLotattr07(CodesConstants.COMMON_WILDCARD);
            }
            if (StringUtils.isNullOrBlank(palletizeData.getTracenumber())){
                palletizeData.setTracenumber(palletizeData.getContainnumber());
            }
            if (StringUtils.isNullOrBlank(palletizeData.getLocationcode())){
                palletizeData.setLocationcode(XcmgAmConstants.LOCATION_CODE_PA0101);
            }
            //
            if (StringUtils.isNullOrBlank(palletizeData.getBatchnumber())){
                palletizeData.setBatchnumber(TextUtils.genBatchNumber());
            }
        }
        if (actionDto!=null){
            if (StringUtils.isNullOrBlank(actionDto.getDivisionCode())){
                actionDto.setDivisionCode(XcmgAmConstants.DIVISION_WH101_CODE);
            }
            if (StringUtils.isNullOrBlank(actionDto.getWorker())){
                actionDto.setWorker(SecurityUtils.getLoginUsername());
            }
        }
    }

    //分组特征码
    public String groupKey(TwiInventoryXwmsDetails lineData){
        String gno="";
        if (lineData==null){
            return gno;
        }
        gno=StringUtils.ifNullOrBlank(lineData.getCustomerCode(), XcmgAmConstants.CUSTOMER_CODE_XCMG_AM)         //货主
                + "/" + lineData.getMaterialCode()
                + "/" + StringUtils.ifNullOrBlank(lineData.getLotattr06(), CodesConstants.COMMON_WILDCARD)   //供应商代码
                + "/" + StringUtils.ifNullOrBlank(lineData.getLotattr07(), CodesConstants.COMMON_WILDCARD);  //WBS

        return gno;
    }

    //
    public PickLabelDto createPickLabel(TwtActTaskList task){
        PickLabelDto pickLabelDto=null;
        if (task==null){
            return pickLabelDto;
        }
        TwmBasMaterial mat=null;
        TwaInventoryLotattr lotattr=null;
        try{
            mat=this.materialService.lookup(task.getMaterialId());
            lotattr=this.lotattrService.lookup(task.getFromLotnoId());
            pickLabelDto=new PickLabelDto();
            pickLabelDto.setMaterialcode(mat.getCode());
            pickLabelDto.setMaterialname(mat.getName());
            pickLabelDto.setUnitcode(CodesConstants.UOM_EACH);
            pickLabelDto.setQuantity(task.getFromQty());
            pickLabelDto.setLotnumber(lotattr.getLotattr07());
            pickLabelDto.setUloc(task.getUdf09());
            pickLabelDto.setSloc(task.getUdf10());
        }catch (Exception e){
            e.printStackTrace();
        }
        return pickLabelDto;
    }

    public String printPickLabel(TwtActTaskList pickTask, PickLabelDto labelDto){
        String m = "";
        if (labelDto==null){
            return m;
        }
        TwtActTaskPrintData printData=null;
        try{
            printData=new TwtActTaskPrintData();
            printData.setGlobalClientId(pickTask.getGlobalClientId());
            printData.setDivisionId(pickTask.getDivisionId());
            printData.setCustomerId(pickTask.getCustomerId());
            printData.setCustomerCode(XcmgAmConstants.CUSTOMER_CODE_XCMG_AM);
            Long templateId = XcmgAmConstants.PRINT_TEMPLATE_ID_PICK_LABEL;
            printData.setTemplateId(templateId);

            printData.setSupplyCode("");
            printData.setDocumentType("");
            printData.setDocumentNumber("");
            printData.setBatchNumber(TextUtils.genBatchNumber());
            printData.setTaskSeqnum(labelDto.getMaterialcode());
            printData.setCopies(1);
            printData.setPrinterCode(XcmgAmConstants.PRINT_PICK_LABEL_A001_8_8_DEF_PRINTER);
            printData.setTaskPriority(WmsConstants.TASK_PRIOR_NORMAL);
            printData.setPrintData(labelDto.toJsonData());
            printData.setPrinterCode("");
            if (!StringUtils.isNullOrBlank(labelDto.getPrinter())){
                printData.setPrinterCode(labelDto.getPrinter().trim());
            }
            printData.setPrintStatus(CodesConstants.COMMON_STATUS_CREATED);
            printData.setRetryTimes(0);

            printData.setCreatedDate(new Date());
            printData.setCreatedBy(SecurityUtils.getLoginUsername());
            printData.setLastModifiedBy(printData.getCreatedBy());
            printData.setLastModifiedDate(printData.getCreatedDate());

            this.printTaskService.save(printData);
        }catch (Exception e){
            e.printStackTrace();
        }
        return m;
    }


/**==================================================================================================================**/
// ---- FUNC/IV/INBOUND
/**==================================================================================================================**/
    //根据码盘收货
    private String fullPalletizeReceive(String containNumber, LocationLineDto toLocation, TaskActionDto actionDto){
        String m = "";
        if (StringUtils.isNullOrBlank(containNumber)){
            m="确认收货失败.托盘码为空.";
            return m;
        }
        if (actionDto==null){
            actionDto=new TaskActionDto();
        }
        if (StringUtils.isNullOrBlank(actionDto.getWorker())){
            actionDto.setWorker(SecurityUtils.getLoginUsername());
        }
        containNumber=containNumber.trim();

        TwtActTaskList task=null;
        List<TwtActTaskList> tasks=null;
        List<TwtActPalletizeList> pals = new ArrayList<>();
        ReceiveActionDto recvActionDto=null;
        //TwaDocAsnHeader asnheader=null;
        //TwaDocAsnDetails asnline=null;
        int index=1;
        FuncReplyData<TaskReportResultDto> reportReplyData=null;
        List<TwtActTransList> trans=null;
        String mline="";
        TaskChangeActionDto changeaction=null;
        try{
            //
            tasks=this.taskService.queryWorkingTasks("", containNumber);
            if ((tasks==null) || (tasks.size()==0)){
                m="找不到上架任务.托盘码:"+containNumber;
                return m;
            }
            changeaction=new TaskChangeActionDto();
            changeaction.setWorkMode(actionDto.getWorkMode());
            changeaction.setWorker(actionDto.getWorker());
            changeaction.setBatchnumber(actionDto.getBatchNumber());
            if (StringUtils.isNullOrBlank(changeaction.getBatchnumber())){
                changeaction.setBatchnumber(TextUtils.genBatchNumber());
            }
            //
            for (TwtActTaskList t:tasks){
                if (t==null){
                    continue;
                }
                if (this.closed(t)){
                    continue;
                }
                if (!WmsConstants.TASK_TYPE_PUTAWAY.equalsIgnoreCase(t.getType())){
                    m="非上架任务.任务号:"+t.getNumber();
                    return m;
                }
                if (t.getRefId()==null){
                    m="非上架任务数据.任务号:"+t.getNumber();
                    return m;
                }
                task=t;
            }

            //
            pals=this.palletizeService.findByContainNumber(containNumber);
            if ((pals==null) || (pals.size()==0)){
                m="找不到码盘记录.托盘码:"+containNumber;
                return m;
            }

            // RECEIVE
            if ((pals!=null) && (pals.size()>0)){
                recvActionDto=new ReceiveActionDto();
                recvActionDto.setLocationCode(toLocation.getLocationCode());
                recvActionDto.setWorker(pals.get(0).getWorker());
                this.receiveService.receive(task.getBatchNumber(), pals, recvActionDto, this.storageBuilder, this.transBuilder);
            }

            //CREATE-ASN
            /**
             asnheader=this.createAsnHeader(task, actionDto.getWorker());
             if (asnheader!=null){
             this.asnService.save(asnheader);
             }
             for (TwtActPalletizeList p:pals){
             if (p==null){
             continue;
             }
             asnline=this.createAsnLine(asnheader, p, toLocation, index);
             if (asnline!=null){
             this.asnDetailsService.save(asnline);
             }
             index++;
             this.palletizeService.delete(p);
             }
             **/
            //
            for (TwtActPalletizeList p:pals){
                if (p==null){
                    continue;
                }
                this.palletizeService.delete(p);
            }
            //
            //

            m = this.taskService.finish(task, this.transBuilder, changeaction);
            if (InforWasXcmgExchangeConstants.SYS_XWMS.equalsIgnoreCase(task.getTaskSchema())){
                trans=this.dyncdataQueryService.queryTransByBatchnumber(task.getBatchNumber());
                if (trans!=null){
                    for (TwtActTransList tran:trans){
                        if (tran==null){
                            continue;
                        }
                        if (!WmsConstants.TRANS_TYPE_RECEIVE.equalsIgnoreCase(tran.getType())){
                            continue;
                        }
                        if (!containNumber.equalsIgnoreCase(tran.getFromContainNumber())){
                            continue;
                        }
                        if ((tran.getEdiSendStatus()!=null)
                                && (!CodesConstants.COMMON_STATUS_CREATED.equalsIgnoreCase(tran.getEdiSendStatus()))){
                            continue;
                        }
                        reportReplyData = this.handleWasTransDataToXwms(tran, false, actionDto.getWorker());
                        mline=InforWasExchangeSupport.errorMessage(reportReplyData);
                        if (StringUtils.isNullOrBlank(mline)){
                            m=m+mline+"\n\r";
                        }
                    }
                }

            }

            //
            /**
             for (TwtActTaskList t:tasks){
             if (t==null){
             continue;
             }
             if (WmsConstants.TASK_STATUS_CLOSE.equalsIgnoreCase(t.getStatus())){
             continue;
             }
             if (WmsConstants.TASK_STATUS_CANCEL.equalsIgnoreCase(t.getStatus())){
             continue;
             }
             t.setStatus(WmsConstants.TASK_STATUS_CLOSE);
             t.setLastModifiedDate(new Date());
             t.setLastModifiedBy(worker);
             this.taskService.save(task);
             }
             **/
        }catch (Exception e){
            e.printStackTrace();
            m="收货异常.异常:"+e.getMessage();
        }
        return m;
    }


/**==================================================================================================================**/
// ---- FUNC/IV/INVENTORY
/**==================================================================================================================**/

    public String taskCompleted(List<TwtActTaskList> tasks, String taskCurrLoctionCode){
        String m = "";

        if ((tasks==null)||(tasks.size()==0)){
            m="tasks is null";
            return m;
        }

        boolean allflag=true;
        Long divisionid=null;
        String containnum=null;
        String tasktype=null;
        Long locid=null;
        for (TwtActTaskList t:tasks){
            if (t==null){
                continue;
            }
            if ((!WmsConstants.TASK_STATUS_CLOSE.equalsIgnoreCase(t.getStatus()))
                    && (!WmsConstants.TASK_STATUS_CANCEL.equalsIgnoreCase(t.getStatus()))){
                allflag=false;
                break;
            }
            if (locid==null){
                locid=t.getToLocId();
                if (t.getPlantoLocId()!=null){
                    locid=t.getPlantoLocId();
                }
            }
            divisionid=t.getDivisionId();
            containnum=t.getFromContainNumber();
            tasktype=t.getType();
        }
        if (!allflag){
            m="task not complete";
            return m;
        }
        List<TwaInventoryDetails> storages=null;
        LocationLineDto loc=null;

        try{
            storages=this.inventoryService.findByContainNumber(containnum);
            if ((storages==null)||(storages.size()==0)){
                if (WmsConstants.TASK_TYPE_PICK.equalsIgnoreCase(tasktype)){
                    return m;
                }
            }
            if (!StringUtils.isNullOrBlank(taskCurrLoctionCode)){
                loc=loc=this.locationResolver.lookup(divisionid, taskCurrLoctionCode.trim());
                m="cant found location master.code:"+taskCurrLoctionCode;
            }else{
                loc=this.locationResolver.lookup(locid);
                m="cant found location master.idd:"+String.valueOf(locid);
            }
            if (loc==null){
                return m;
            }
            m="";
            allflag=true;
            for (TwaInventoryDetails d:storages){
                if (d==null){
                    continue;
                }
                if (!d.getLocId().equals(loc.getLocationId())){
                    allflag=false;
                }
            }
            if (allflag){
                m=XcmgAmConstants.RESULT_CODE_EDI_WARN_GONO;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return m;
    }

    public String createHoldMoveTask(String divisionCode, TwtActTaskList task, String worker){
        String m = "";
        if (task==null){
            return m;
        }
        if (task.getId()!=null){
            return m;
        }
        if (StringUtils.isNullOrBlank(task.getFromLocSeq())){
            return m;
        }
        if (StringUtils.isNullOrBlank(task.getToLocSeq())){
            return m;
        }
        try{
            task.setFromLocSeq(task.getFromLocSeq().trim());
            task.setToLocSeq(task.getToLocSeq().trim());
            Long divisionid=this.divisionService.retrieveOn(divisionCode, XcmgAmConstants.DIVISION_WH101_ID);
            LocationLineDto loc=this.locationResolver.lookup(divisionid, task.getFromLocSeq());
            if (loc==null){
                m="无效的库位.库位码:"+task.getFromLocSeq();
                return m;
            }
            task.setFromLocId(loc.getLocationId());
            task.setFromLocSeq(loc.getPaSeqCode());
            loc=this.locationResolver.lookup(divisionid, task.getToLocSeq());
            if (loc==null){
                m="无效的库位.库位码:"+task.getToLocSeq();
                return m;
            }
            task.setToLocId(loc.getLocationId());
            task.setToLocSeq(loc.getPaSeqCode());
            //
            task.setGlobalClientId(XcmgAmConstants.CLIENT_ID_XCMG);
            task.setCustomerId(XcmgAmConstants.CUSTOMER_ID_XCMG_AM);
            task.setDivisionId(divisionid);
            if (StringUtils.isNullOrBlank(task.getNumber())){
                task.setNumber(this.seqService.next(WmsConstants.SEQUENCE_NAME_ACT_TASK));
            }
            //
            task.setFromContainNumber(task.getFromContainNumber().trim());
            if (StringUtils.isNullOrBlank(task.getFromTraceNumber())){
                task.setFromTraceNumber(task.getFromContainNumber());
            }
            if (StringUtils.isNullOrBlank(task.getToContainNumber())){
                task.setToContainNumber(task.getFromContainNumber());
            }
            if (StringUtils.isNullOrBlank(task.getToTraceNumber())){
                task.setToTraceNumber(task.getToContainNumber());
            }
            if (StringUtils.isNullOrBlank(task.getPlantoContainNumber())){
                task.setPlantoContainNumber(task.getToContainNumber());
            }
            if (StringUtils.isNullOrBlank(task.getPlantoTraceNumber())){
                task.setPlantoTraceNumber(task.getPlantoContainNumber());
            }
            task.setReleaseStatus(CodesConstants.COMMON_RELEASE_STATUS_HOLDING);
            //

            task.setNumberSeq("0010");
            task.setCategory(WmsConstants.TASK_TYPE_MOVE);
            task.setType(WmsConstants.TASK_TYPE_MOVE);

            task.setTaskMode(null);
            task.setTaskClass(null);
            //task.setTaskAction(XcmgAmConstants.WCS_TASK_ACTION_RETURN);
            task.setTaskFeature(null);
            task.setGroupNumber(null);
            task.setMaterialId(XcmgAmConstants.MATERIAL_ID_EPAL);
            task.setDocId(null);
            task.setDocDetailsId(null);
            task.setWaveId(null);
            task.setWaveDetailsId(null);
            task.setDocNumber(null);
            task.setDocLinenumber(null);
            task.setStatus(WmsConstants.TASK_STATUS_CREATE);
            task.setStorageId(null);
            task.setFromLotnoId(null);
            task.setFromLotnoNumber(null);
            //

            task.setFromQty(BigDecimal.ONE);
            task.setFromQtyEach(task.getFromQty());
            task.setFromPackId(null);
            task.setFromUomCode(null);
            task.setFromPrice(null);
            task.setFromGrossweight(null);
            task.setFromNetweight(null);
            task.setFromCubic(null);

            task.setToDivisionId(task.getDivisionId());
            task.setToLotnoId(task.getFromLotnoId());
            task.setToLotnoNumber(task.getFromLotnoNumber());
            //

            task.setToQty(task.getFromQty());
            task.setToQtyEach(task.getToQty());
            task.setToPackId(task.getFromPackId());
            task.setToUomCode(task.getFromUomCode());
            task.setToPrice(task.getFromPrice());
            task.setToGrossweight(task.getFromGrossweight());
            task.setToNetweight(task.getFromNetweight());
            task.setToCubic(task.getFromCubic());

            //
            task.setPlantoQty(null);
            task.setPlantoQtyEach(task.getPlantoQty());
            task.setPlantoPackId(null);
            task.setPlantoUomCode(null);
            task.setPlantoLocSeq(task.getToLocSeq());
            task.setTaskPrior(WmsConstants.TASK_PRIOR_NORMAL);
            task.setTaskSchema(null);
            task.setPrintStatus(null);
            task.setBatchNumber(TextUtils.genBatchNumber());
            task.setBulkNumber(null);
            task.setRefType(null);
            task.setRefId(null);
            task.setRefAllocationId(null);
            task.setRefParentTaskId(null);
            task.setRefPreTaskId(null);
            task.setRefNextTaskId(null);
            task.setRefOpenTransId(null);
            task.setRefCloseTransId(null);
            task.setOpenTime(null);
            task.setOpenBy(null);
            task.setPlantoTime(null);
            task.setPlantoBy(null);
            task.setTakeTime(null);
            task.setTakeBy(null);
            task.setHoldTime(null);
            task.setHoldBy(null);
            task.setCloseTime(null);
            task.setCloseBy(null);
            task.setErrorCode(null);
            task.setErrorMessages(null);
            task.setLotattr01(null);
            task.setLotattr02(null);
            task.setLotattr03(null);
            task.setLotattr04(null);
            task.setLotattr05(null);
            task.setLotattr06(null);
            task.setLotattr07(null);
            task.setLotattr08(null);
            task.setLotattr09(null);
            task.setLotattr10(null);
            task.setLotattr11(null);
            task.setLotattr12(null);
            task.setLotattr13(null);
            task.setLotattr14(null);
            task.setLotattr15(null);
            task.setLotattr16(null);

            task.setUdf01(null);
            task.setUdf02(null);
            task.setUdf03(null);
            task.setUdf04(null);
            task.setUdf05(null);
            task.setUdf06(null);
            task.setUdf07(null);
            task.setUdf08(null);
            task.setUdf09(null);
            task.setUdf10(null);

            task.setEdiSendTime(null);
            task.setEdiSendStatus(CodesConstants.COMMON_STATUS_CREATED);
            task.setEdiReceiveTime(null);
            task.setEdiReceiveStatus(null);
            task.setEdiReceiveMsg(null);

            task.setDelFlag(false);
            task.setEditable(1);
            task.setNotes(null);

            task.setCreatedDate(new Date());
            task.setCreatedBy(worker);
            task.setLastModifiedDate(task.getCreatedDate());
            task.setLastModifiedBy(task.getCreatedBy());
            this.taskService.save(task);
        }catch (Exception e){
            m="生成任务失败.异常:"+e.getMessage();
        }
        return m;
    }

    //生成盘点明细
    public String checkout(Long countId,  String worker){
        String m = "";
        if (countId==null){
            m="请指定有效的盘点单.";
            return m;
        }
        if (StringUtils.isNullOrBlank(worker)){
            worker=SecurityUtils.getLoginUsername();
        }
        TwaDocCoHeader header=null;
        List<TwaDocCoDetails> lines=null;
        Date fmdate=null;
        Date todate=null;
        String fmcontnum=null;
        String tocontnum=null;
        List<TwaInventoryDetails> storages=null;
        Map<Long, TwaInventoryLotattr> lotattrs=new HashMap<>();
        try{
            header=this.coService.findById(countId);
            if (header==null){
                m="找不到盘点单,请确认是否已删除.ID:"+String.valueOf(countId);
                return m;
            }
            if (!WmsConstants.CO_STATUS_CREATE.equalsIgnoreCase(header.getStatus())){
                m="盘点单非创建状态,无法生成盘点明细.单号:"+header.getDocumentNumber();
                return m;
            }
            /**
            if (header.getCheckoutTime()!=null){
                m="盘点单已经生成明细,无法多次生成.单号:"+header.getDocumentNumber();
                return m;
            }
            if (WmsConstants.CO_TYPE_NORMAL.equalsIgnoreCase(header.getType())){
                m="请在库存明细中,选定明细行生成盘点明细.";
                return m;
            }
            lines=this.coDetailsService.findByDocumentId(header.getId());
            if ((lines!=null)&& (lines.size()>0)){
                m="盘点单已经生成明细,无法多次生成.单号:"+header.getDocumentNumber();
                return m;
            }
             **/
            //非Normal盘点
            if (!WmsConstants.CO_TYPE_NORMAL.equalsIgnoreCase(header.getType())){
                m=this.storageService.checkout(header.getId(), worker);
            }else {
                if (header.getFromQty()!=null){
                    fmcontnum=header.getFromQty().stripTrailingZeros().toPlainString();
                }
                if (header.getToQty()!=null){
                    tocontnum=header.getToQty().stripTrailingZeros().toPlainString();
                }
                if (!StringUtils.isNullOrBlank(fmcontnum)){
                    if (StringUtils.isNullOrBlank(tocontnum)){
                        tocontnum=fmcontnum;
                    }
                }
                if (!StringUtils.isNullOrBlank(tocontnum)){
                    if (StringUtils.isNullOrBlank(fmcontnum)){
                        fmcontnum=tocontnum;
                    }
                }
                if ((!StringUtils.isNullOrBlank(fmcontnum)) && (!StringUtils.isNullOrBlank(tocontnum))){
                    if (fmcontnum.compareTo(tocontnum)>0){
                        m="盘点单参数无效:起始容器号大于结束容器号.单号:"+header.getDocumentNumber();
                        return m;
                    }
                }
                /**
                if (!StringUtils.isNullOrBlank(header.getUdf05())){
                    fmdate=DateUtils.parse(header.getUdf05().trim(), DateUtils.FORMAT_DATE_YYYYMMDD);
                    if (fmdate==null){
                        m="盘点单参数无效:起始收货时间无效.单号:"+header.getDocumentNumber();
                        return m;
                    }
                }
                if (!StringUtils.isNullOrBlank(header.getUdf06())){
                    todate=DateUtils.parse(header.getUdf06().trim(), DateUtils.FORMAT_DATE_YYYYMMDD);
                    if (todate==null){
                        m="盘点单参数无效:结束收货时间无效.单号:"+header.getDocumentNumber();
                        return m;
                    }
                }
                 **/
                fmdate=header.getFromTime();
                todate=header.getToTime();
                if (fmdate!=null){
                    if (todate==null){
                        todate=fmdate;
                    }
                }
                if (todate!=null){
                    if (fmdate==null){
                        fmdate=todate;
                    }
                }
                if ((fmdate!=null) && (todate!=null)){
                    if (fmdate.compareTo(todate)>0){
                        m="盘点单参数无效:起始收货日期大于结束收货日期.单号:"+header.getDocumentNumber();
                        return m;
                    }
                }
                storages=this.dyncdataQueryService.queryInventory(header.getDivisionId(), null, fmcontnum, tocontnum, fmdate, todate);
                if ((storages==null) || (storages.size()==0)){
                    return m;
                }
                if (storages.size()>(XcmgAmConstants.COUNT_MAX_COTAINER_COUNT*4)){
                    m="盘点物料太多，请重新设置盘点条件。单号:"+header.getDocumentNumber();
                    return m;
                }
                this.storageService.checkout(header, storages, lotattrs, worker);
            }
            header.setCheckoutTime(new Date());
            header.setLastModifiedDate(header.getCheckoutTime());
            header.setLastModifiedBy(worker);

            this.coService.save(header);
        }catch (Exception e){
            m="生成盘点明细失败.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    public String confirmCount(Long taskid, BigDecimal quantity, BigDecimal countQuantity, TaskActionDto actionDto){
        String m = "";

        if (taskid==null){
            m="请获取盘点任务进行确认.";
            return m;
        }

        String workedflag=this.countTaskCheckedCache.getIfPresent(taskid);
        if ((workedflag!=null) && (CodesConstants.COMMON_FLAG_YES.equalsIgnoreCase(workedflag))){
            return m;
        }

        String worker=SecurityUtils.getLoginUsername();
        if ((actionDto!=null)&&(!StringUtils.isNullOrBlank(actionDto.getWorker()))){
            worker=actionDto.getWorker().trim();
        }

        TwtActTaskList task=null;
        TwaDocCoDetails line=null;
        TwaDocCoHeader header=null;
        try{
            task=this.taskService.findById(taskid);
            if (task==null){
                m="找不到盘点任务,请确认是否已经删除.任务ID:"+String.valueOf(taskid);
                return m;
            }
            if (!WmsConstants.TASK_TYPE_COUNT.equalsIgnoreCase(task.getType())){
                m="非到盘点任务,请确认.任务号:"+task.getNumber();
                return m;
            }
            if ((WmsConstants.TASK_STATUS_CLOSE.equalsIgnoreCase(task.getStatus()))
                    || (WmsConstants.TASK_STATUS_CANCEL.equalsIgnoreCase(task.getStatus()))){
                m="盘点任务已经完成或已取消,不能重复确认.任务号:"+task.getNumber();
                return m;
            }
            if (countQuantity==null){
                countQuantity=task.getToQty();
            }
            if ((countQuantity==null) || (countQuantity.compareTo(BigDecimal.ZERO)<0)){
                m="无效的盘点数量,数量不能小于0.任务号:"+task.getNumber();
                return m;
            }
            if (task.getDocDetailsId()!=null){
                line=this.coDetailsService.findById(task.getDocDetailsId());
            }
            if (line==null){
                m="找不到对应的盘点明细,请确认是否删除.盘点行ID:"+String.valueOf(task.getDocDetailsId());
                return m;
            }
            if (WmsConstants.CO_STATUS_CLOSE.equalsIgnoreCase(line.getLineStatus())){
                m="盘点明细已经完成.盘点行号:"+line.getLineNumber();
                return m;
            }
            if (WmsConstants.CO_STATUS_CANCELL.equalsIgnoreCase(line.getLineStatus())){
                m="盘点明细已经取消.盘点行号:"+line.getLineNumber();
                return m;
            }
            if (WmsConstants.CO_STATUS_DELIVER.equalsIgnoreCase(line.getLineStatus())){
                m="盘点明细已经发布调账.盘点行号:"+line.getLineNumber();
                return m;
            }
            task.setToQty(countQuantity);
            task.setToQtyEach(task.getToQty());
            task.setStatus(WmsConstants.TASK_STATUS_CLOSE);
            task.setLastModifiedBy(worker);
            task.setLastModifiedDate(new Date());
            this.taskService.save(task);

            line.setQtyCount(countQuantity);
            line.setCountTime(new Date());
            line.setCountBy(worker);
            line.setLineStatus(WmsConstants.CO_STATUS_COUNT);
            line.setLastModifiedBy(worker);
            line.setLastModifiedDate(line.getCountTime());
            this.coDetailsService.save(line);

            this.coService.refreshStatus(line.getHeaderId());

            if (XcmgAmConstants.COUNT_TRANSFER_MODE_COUNT_MAKE_CHANGE.equalsIgnoreCase(this.countTransferMode)){
                header=this.coService.findById(line.getHeaderId());
                if (header==null){
                    return m;
                }
                if (WmsConstants.CO_STATUS_CLOSE.equalsIgnoreCase(header.getStatus())){
                    m="盘点确认成功,但自动调账失败:盘点单已经关闭.单号:"+header.getDocumentNumber();
                    return m;
                }
                if (WmsConstants.CO_STATUS_CANCELL.equalsIgnoreCase(header.getStatus())){
                    m="盘点确认成功,但自动调账失败:盘点单已经取消.单号:"+header.getDocumentNumber();
                    return m;
                }
                if (WmsConstants.CO_STATUS_DELIVER.equalsIgnoreCase(header.getStatus())){
                    m="盘点确认成功,但自动调账失败:盘点单已经发布.单号:"+header.getDocumentNumber();
                    return m;
                }
                m=this.deliverCount(task.getBatchNumber(), line, worker, true);
                if (!StringUtils.isNullOrBlank(m)){
                    m="盘点确认成功,但自动调账失败:"+m;
                    return m;
                }
                this.countTaskCheckedCache.put(taskid, CodesConstants.COMMON_FLAG_YES);
            }
        }catch (Exception e){
            m="确认盘点失败.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }


/**==================================================================================================================**/
// ---- FUNC/X/INBOUND
 /**==================================================================================================================**/
    //
    //创建码盘数据
    public TwtActPalletizeList createPalletizeData(PalletizeChangeData palletizeData, TwmBasMaterial material, TaskActionDto actionDto){
         TwtActPalletizeList palletize=null;
         if (palletizeData==null){
             return palletize;
         }
         if (material==null){
             return palletize;
         }
         Long divisionid=this.divisionService.retrieve(palletizeData.getDivisioncode());
         String locationcode=palletizeData.getLocationcode().trim();
         LocationLineDto loc=null;
         try{
             loc=this.locationResolver.lookup(divisionid, locationcode);
             if (loc==null){
                 return palletize;
             }
             palletize=new TwtActPalletizeList();
             palletize.setGlobalClientId(material.getGlobalClientId());
             palletize.setDivisionId(divisionid);
             palletize.setCustomerId(material.getCustomerId());
             palletize.setBatchNumber(palletizeData.getBatchnumber());
             palletize.setTransId(null);
             palletize.setLineSeq(null); //
             palletize.setWorker(palletizeData.getCreatesource());
             palletize.setWorkingType(null);
             palletize.setWorkMode(actionDto.getWorkMode());
             palletize.setContainNumber(palletizeData.getContainnumber());
             palletize.setTraceNumber(palletizeData.getTracenumber());
             palletize.setLineStatus(WmsConstants.TASK_STATUS_CREATE);
             //
             palletize.setDocumentId(null);
             palletize.setDocumentDetailsId(null);
             palletize.setDocNumber(null);
             palletize.setDocLinenumber(null);
             palletize.setDocType(palletizeData.getCreatetype());

             //
             palletize.setMaterialId(material.getId());
             palletize.setMaterialCode(material.getCode());
             palletize.setQty(palletizeData.getQuantity());
             palletize.setQtyEach(palletize.getQty());
             palletize.setQtyCaseCapacity(palletize.getQtyEach());
             palletize.setQtyPalletCapacity(palletize.getQtyCaseCapacity());
             palletize.setPackId(material.getPackId());
             palletize.setPackCode(null); //
             palletize.setPackType(CodesConstants.UOM_EACH);
             palletize.setUomCode(CodesConstants.UOM_EACH);

             palletize.setLotNumber(palletizeData.getLotattr05());
             palletize.setLocationId(loc.getLocationId());
             palletize.setLocationCode(locationcode);
             palletize.setPlantoLocationId(null);
             palletize.setPlantoLocationCode(null);

             palletize.setSupplierCode(palletizeData.getLotattr06());  //供应商
             palletize.setProductionDate(null);
             palletize.setQcStatus(WmsConstants.QC_STATUS_PASS);
             palletize.setRefNumber(palletizeData.getReservenumber());

             palletize.setPrice(null);
             palletize.setCubic(null);
             palletize.setGrossweight(null);
             palletize.setNetweight(null);
             palletize.setLen(null);
             palletize.setWidth(null);
             palletize.setHeight(null);

             palletize.setLotattr01(null);
             palletize.setLotattr02(null);
             palletize.setLotattr03(null);
             palletize.setLotattr04(null);
             palletize.setLotattr05(palletizeData.getLotattr05());
             palletize.setLotattr06(palletizeData.getLotattr06());
             palletize.setLotattr07(palletizeData.getLotattr07());
             palletize.setLotattr08(null);
             palletize.setLotattr09(null);
             palletize.setLotattr10(null);
             palletize.setLotattr11(null);
             palletize.setLotattr12(null);
             palletize.setLotattr13(null);
             palletize.setLotattr14(null);
             palletize.setLotattr15(null);
             palletize.setLotattr16(null);

             palletize.setUdf01(palletizeData.getUdf01());
             palletize.setUdf02(palletizeData.getUdf02());
             palletize.setUdf03(palletizeData.getUdf03());
             palletize.setUdf04(palletizeData.getUdf04());
             palletize.setUdf05(palletizeData.getUdf05());
             palletize.setUdf06(palletizeData.getUdf06());
             palletize.setUdf07(palletizeData.getUdf07());
             palletize.setUdf08(palletizeData.getUdf08());
             palletize.setUdf09(palletizeData.getUdf09());
             palletize.setUdf10(palletizeData.getUdf10());

             palletize.setCheckedValue(null);
             palletize.setCheckedCode(null);
             palletize.setCheckedMsg(null);
             palletize.setEdiSendTime(null);
             palletize.setEdiSendStatus(CodesConstants.COMMON_STATUS_CREATED);
             palletize.setEdiReceiveTime(null);
             palletize.setEdiReceiveStatus(null);
             palletize.setEdiReceiveMsg(null);

             palletize.setNotes(null);
             palletize.setCreatedBy(actionDto.getWorker());
             palletize.setCreatedDate(new Date());
             palletize.setLastModifiedBy(palletize.getCreatedBy());
             palletize.setLastModifiedDate(palletize.getCreatedDate());

             this.palletizeService.save(palletize);
         }catch (Exception e){
             e.getMessage();
         }
         return palletize;
     }

    //创建码盘数据
    public TwtActPalletizeList createPalletizeData(PalletizeChangeData palletizeData, TwaDocAsnHeader header, TwaDocAsnDetails details, TwmBasMaterial material, TaskActionDto actionDto){
        return this.createPalletizeData(palletizeData, header, details, material, palletizeData.getQuantity(), palletizeData.getUdf07(), actionDto);
    }

    //创建码盘数据
    private TwtActPalletizeList createPalletizeData(PalletizeChangeData palletizeData, TwaDocAsnHeader header, TwaDocAsnDetails details, TwmBasMaterial material, BigDecimal quantity, String xwmsLotnumber, TaskActionDto actionDto){
        TwtActPalletizeList palletize=null;
        if (palletizeData==null){
            return palletize;
        }
        if (material==null){
            return palletize;
        }
        if ((quantity==null)||(quantity.compareTo(BigDecimal.ZERO))<=0){
            quantity=palletizeData.getQuantity();
        }
        if ((quantity==null)||(quantity.compareTo(BigDecimal.ZERO))<=0){
            return palletize;
        }
        if (StringUtils.isNullOrBlank(xwmsLotnumber)){
            xwmsLotnumber=palletizeData.getUdf07();
        }

        Long divisionid=this.divisionService.retrieve(palletizeData.getDivisioncode());
        String locationcode=palletizeData.getLocationcode().trim();
        LocationLineDto loc=null;
        try{
            loc=this.locationResolver.lookup(divisionid, locationcode);
            if (loc==null){
                return palletize;
            }
            palletize=new TwtActPalletizeList();
            palletize.setGlobalClientId(material.getGlobalClientId());
            palletize.setDivisionId(divisionid);
            palletize.setCustomerId(material.getCustomerId());
            palletize.setBatchNumber(palletizeData.getBatchnumber());
            palletize.setTransId(null);
            palletize.setLineSeq(details.getLineNumber()); //
            palletize.setWorker(palletizeData.getCreatesource());
            palletize.setWorkingType(null);
            palletize.setWorkMode(actionDto.getWorkMode());
            palletize.setContainNumber(palletizeData.getContainnumber());
            palletize.setTraceNumber(palletizeData.getTracenumber());
            palletize.setLineStatus(WmsConstants.TASK_STATUS_CREATE);
            //
            palletize.setDocumentId(header.getId());
            palletize.setDocumentDetailsId(details.getId());
            palletize.setDocNumber(header.getDocumentNumber());
            palletize.setDocLinenumber(details.getLineNumber());
            palletize.setDocType(palletizeData.getCreatetype());

            //
            palletize.setMaterialId(material.getId());
            palletize.setMaterialCode(material.getCode());
            palletize.setQty(quantity);
            palletize.setQtyEach(palletize.getQty());
            palletize.setQtyCaseCapacity(palletize.getQtyEach());
            palletize.setQtyPalletCapacity(palletize.getQtyCaseCapacity());
            palletize.setPackId(material.getPackId());
            palletize.setPackCode(null); //
            palletize.setPackType(CodesConstants.UOM_EACH);
            palletize.setUomCode(details.getUomCode());

            palletize.setLotNumber(palletizeData.getLotattr05());
            palletize.setLocationId(loc.getLocationId());
            palletize.setLocationCode(locationcode);
            palletize.setPlantoLocationId(null);
            palletize.setPlantoLocationCode(null);

            palletize.setSupplierCode(palletizeData.getLotattr06());  //供应商
            palletize.setProductionDate(null);
            palletize.setQcStatus(WmsConstants.QC_STATUS_PASS);
            palletize.setRefNumber(palletizeData.getReservenumber());

            palletize.setPrice(null);
            palletize.setCubic(null);
            palletize.setGrossweight(null);
            palletize.setNetweight(null);
            palletize.setLen(null);
            palletize.setWidth(null);
            palletize.setHeight(null);

            palletize.setLotattr01(null);
            palletize.setLotattr02(null);
            palletize.setLotattr03(null);
            palletize.setLotattr04(null);
            palletize.setLotattr05(palletizeData.getLotattr05());
            palletize.setLotattr06(palletizeData.getLotattr06());
            palletize.setLotattr07(palletizeData.getLotattr07());
            palletize.setLotattr08(null);
            palletize.setLotattr09(null);
            palletize.setLotattr10(null);
            palletize.setLotattr11(null);
            palletize.setLotattr12(null);
            palletize.setLotattr13(null);
            palletize.setLotattr14(null);
            palletize.setLotattr15(null);
            palletize.setLotattr16(null);

            palletize.setUdf01(palletizeData.getUdf01());
            palletize.setUdf02(palletizeData.getUdf02());
            palletize.setUdf03(palletizeData.getUdf03());
            palletize.setUdf04(palletizeData.getUdf04());
            palletize.setUdf05(palletizeData.getUdf05());
            palletize.setUdf06(palletizeData.getUdf06());
            palletize.setUdf07(xwmsLotnumber);
            palletize.setUdf08(palletizeData.getUdf08());
            palletize.setUdf09(palletizeData.getUdf09());
            palletize.setUdf10(palletizeData.getUdf10());

            palletize.setCheckedValue(null);
            palletize.setCheckedCode(null);
            palletize.setCheckedMsg(null);
            palletize.setEdiSendTime(null);
            palletize.setEdiSendStatus(CodesConstants.COMMON_STATUS_CREATED);
            palletize.setEdiReceiveTime(null);
            palletize.setEdiReceiveStatus(null);
            palletize.setEdiReceiveMsg(null);

            palletize.setNotes(header.getNotes());
            palletize.setCreatedBy(actionDto.getWorker());
            palletize.setCreatedDate(new Date());
            palletize.setLastModifiedBy(palletize.getCreatedBy());
            palletize.setLastModifiedDate(palletize.getCreatedDate());

            this.palletizeService.save(palletize);
        }catch (Exception e){
            e.getMessage();
        }
        return palletize;
    }
    //
    private TwaDocAsnHeader createAsnHeader(TwtActTaskList task, String worker){
        TwaDocAsnHeader header = null;
        if (task==null){
            return header;
        }
        header=new TwaDocAsnHeader();
        header.setGlobalClientId(task.getGlobalClientId());
        header.setCustomerId(task.getCustomerId());
        header.setDivisionId(task.getDivisionId());
        header.setDocumentNumber(this.seqService.next(WmsConstants.SEQUENCE_NAME_DOC_ASN));
        header.setType(WmsConstants.ASN_TYPE_PURCHASE_ORDER);
        header.setStatus(WmsConstants.ASN_STATUS_RECEIVE);
        header.setArrivalTime(new Date());
        header.setFirstReceiveTime(new Date());
        header.setCreateSource(InforWasXcmgExchangeConstants.SYS_XWMS);
        if (!StringUtils.isNullOrBlank(task.getTaskSchema())){
            header.setCreateSource(task.getTaskSchema().trim());
        }
        header.setCategory(XcmgAmConstants.WORK_SOURCE_PO);
        if (!StringUtils.isNullOrBlank(task.getCategory())){
            header.setCategory(task.getCategory().trim());
        }

        header.setDocPrior(WmsConstants.TASK_PRIOR_NORMAL);
        header.setSupplierCode(task.getLotattr06());
        header.setReleaseStatus(CodesConstants.COMMON_RELEASE_STATUS_CREATED);
        header.setUdf01(task.getUdf01());
        header.setUdf02(task.getUdf02());
        header.setUdf03(task.getUdf03());
        header.setUdf04(task.getUdf04());
        header.setUdf05(task.getUdf05());
        header.setUdf06(task.getUdf06());
        header.setUdf07(task.getUdf07());
        header.setUdf08(task.getUdf08());
        header.setUdf09(task.getUdf09());
        header.setUdf10(task.getUdf10());

        header.setEdiSendStatus(CodesConstants.COMMON_STATUS_CREATED);
        header.setEdiSendTime(null);
        header.setEdiReceiveStatus(CodesConstants.COMMON_STATUS_CREATED);
        header.setEdiReceiveTime(null);
        header.setEdiReceiveMsg(null);

        header.setDelFlag(false);
        header.setEditable(true);
        header.setEnabled(true);
        header.setNotes(null);

        header.setCreatedBy(worker);
        header.setCreatedDate(new Date());
        header.setLastModifiedBy(header.getCreatedBy());
        header.setLastModifiedDate(header.getCreatedDate());

        return header;
    }

    private TwaDocAsnDetails createAsnLine(TwaDocAsnHeader header, TwtActPalletizeList palletize, LocationLineDto toloc, int index) {
        TwaDocAsnDetails line = null;
        if (header == null) {
            return line;
        }
        if (palletize == null) {
            return line;
        }
        TwmBasMaterial mat=null;
        try{
            mat=this.materialService.lookup(palletize.getMaterialId());
            if (mat==null){
                return line;
            }
            line=new TwaDocAsnDetails();
            line.setHeaderId(header.getId());
            line.setLineNumber(String.format("%02d", (index*10)));
            line.setLineStatus(WmsConstants.ASN_STATUS_RECEIVE);
            line.setRefDocNumber(null);
            line.setRefLineNumber(null);
            line.setMaterialId(palletize.getMaterialId());
            line.setMaterialCode(palletize.getMaterialCode());
            line.setMaterialName(mat.getName());

            line.setQtyOrdered(palletize.getQty());
            line.setQtyOrderedEach(palletize.getQtyEach());
            line.setQtyPalletized(palletize.getQty());
            line.setQtyPalletizedEach(palletize.getQtyEach());
            line.setQtyReceived(palletize.getQty());
            line.setQtyReceivedEach(palletize.getQtyEach());
            line.setQtyRejected(BigDecimal.ZERO);
            line.setQtyRejectedEach(line.getQtyRejected());
            line.setPackId(mat.getPackId());
            line.setUomCode(palletize.getUomCode());
            line.setContainNumber(palletize.getContainNumber());
            line.setTraceNumber(palletize.getTraceNumber());
            line.setOverReceiveFlag(CodesConstants.COMMON_FLAG_NO);
            line.setReceiveLocId(toloc.getLocationId());
            line.setReceiveLocCode(toloc.getLocationCode());
            line.setTotalPrice(BigDecimal.ZERO);
            line.setTotalCubic(BigDecimal.ZERO);
            line.setTotalGrossweight(BigDecimal.ZERO);
            line.setTotalNetweight(BigDecimal.ZERO);
            line.setTotalPrice(BigDecimal.ZERO);
            line.setProductStatus(null);
            line.setProductStatusDescr(null);
            line.setReleaseStatus(CodesConstants.COMMON_RELEASE_STATUS_CREATED);
            line.setReserveStatus(null);
            line.setFirstReceiveTime(header.getFirstReceiveTime());
            line.setLastReceiveTime(null);

            line.setLotattr05(palletize.getLotattr05());
            line.setLotattr06(palletize.getLotattr06());
            line.setLotattr07(palletize.getLotattr07());

            line.setUdf01(palletize.getUdf01());
            line.setUdf02(palletize.getUdf02());
            line.setUdf03(palletize.getUdf03());
            line.setUdf04(palletize.getUdf04());
            line.setUdf05(palletize.getUdf05());
            line.setUdf06(palletize.getUdf06());
            line.setUdf07(palletize.getUdf07());
            line.setUdf08(palletize.getUdf08());
            line.setUdf09(palletize.getUdf09());
            line.setUdf10(palletize.getUdf10());

            line.setDEdi01(null);
            line.setDEdi02(null);
            line.setDEdi03(null);
            line.setDEdi04(null);
            line.setDEdi05(null);
            line.setDEdi06(null);
            line.setDEdi07(null);
            line.setDEdi08(null);
            line.setDEdi09(null);
            line.setDEdi10(null);
            line.setDEdi11(null);
            line.setDEdi12(null);
            line.setDEdi13(null);
            line.setDEdi14(null);
            line.setDEdi15(null);
            line.setDEdi16(null);
            line.setDEdi17(null);
            line.setDEdi18(null);
            line.setDEdi19(null);
            line.setDEdi20(null);
            line.setDelFlag(false);
            line.setNotes(null);

            line.setCreatedBy(header.getCreatedBy());
            line.setCreatedDate(new Date());
            line.setLastModifiedBy(line.getCreatedBy());
            line.setLastModifiedDate(line.getCreatedDate());
        }catch (Exception e){
            e.printStackTrace();
        }
        return line;
    }

    private TwaDocAsnHeader takeAsnHeader(Long divisionId, PalletizeChangeData palletizeData, TwmBasMaterial material, String worker){
        TwaDocAsnHeader header = null;
        if (palletizeData==null){
            return header;
        }
        if (material==null){
            return header;
        }
        if (divisionId==null){
            divisionId=XcmgAmConstants.DIVISION_WH101_ID;
        }
        Long docid=null;
        List<TwaDocAsnHeader> headers=null;
        try{
            //cache
            docid=WorkDataHolders.get(divisionId).takeAsnByPalletContainnumber(palletizeData.getContainnumber());
            if (docid!=null){
                header=this.asnService.findById(docid);
                if ((header!=null)
                        && (WmsConstants.ASN_STATUS_CREATE.equalsIgnoreCase(header.getStatus()))
                        && (palletizeData.getContainnumber().equalsIgnoreCase(header.getDeliveryContainerNum()))){
                    return header;
                }
            }
            //query
            headers=this.dyncdataQueryService.queryAsnHeader(divisionId, palletizeData.getContainnumber());
            if ((headers!=null) && (headers.size()>0)){
                for (TwaDocAsnHeader h:headers){
                    if (h==null){
                        continue;
                    }
                    header=h;
                }
                if (header!=null){
                    WorkDataHolders.get(divisionId).savePalletContainnumberWithAsn(palletizeData.getContainnumber(), header.getId());
                    return header;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        header=new TwaDocAsnHeader();
        header.setGlobalClientId(material.getGlobalClientId());
        header.setCustomerId(material.getCustomerId());
        header.setDivisionId(divisionId);
        header.setDocumentNumber(this.seqService.next(WmsConstants.SEQUENCE_NAME_DOC_ASN));
        header.setType(WmsConstants.ASN_TYPE_PURCHASE_ORDER);
        header.setStatus(WmsConstants.ASN_STATUS_CREATE);
        header.setArrivalTime(new Date());
        header.setFirstReceiveTime(new Date());
        header.setCreateSource(InforWasXcmgExchangeConstants.SYS_XWMS);
        if (!StringUtils.isNullOrBlank(palletizeData.getCreatesource())){
            header.setCreateSource(palletizeData.getCreatesource().trim());
        }
        header.setCategory(XcmgAmConstants.WORK_SOURCE_PO);
        if (!StringUtils.isNullOrBlank(palletizeData.getCreatetype())) {
            header.setCategory(palletizeData.getCreatetype().trim());
        }
        header.setDocPrior(WmsConstants.TASK_PRIOR_NORMAL);
        header.setSupplierCode(palletizeData.getLotattr06());
        header.setReleaseStatus(CodesConstants.COMMON_RELEASE_STATUS_CREATED);

        header.setDeliveryContainerNum(palletizeData.getContainnumber());
        header.setDeliveryLastStatus(WmsConstants.ASN_STATUS_PART_PALLET);

        header.setUdf01(palletizeData.getUdf01());
        header.setUdf02(palletizeData.getUdf02());
        header.setUdf03(palletizeData.getUdf03());
        header.setUdf04(palletizeData.getUdf04());
        header.setUdf05(palletizeData.getUdf05());
        header.setUdf06(palletizeData.getUdf06());
        header.setUdf07(palletizeData.getUdf07());
        header.setUdf08(palletizeData.getUdf08());
        header.setUdf09(palletizeData.getUdf09());
        header.setUdf10(palletizeData.getUdf10());

        header.setEdiSendStatus(CodesConstants.COMMON_STATUS_CREATED);
        header.setEdiSendTime(null);
        header.setEdiReceiveStatus(CodesConstants.COMMON_STATUS_CREATED);
        header.setEdiReceiveTime(null);
        header.setEdiReceiveMsg(null);

        header.setDelFlag(false);
        header.setEditable(true);
        header.setEnabled(true);
        header.setNotes(null);

        header.setCreatedBy(worker);
        header.setCreatedDate(new Date());
        header.setLastModifiedBy(header.getCreatedBy());
        header.setLastModifiedDate(header.getCreatedDate());

        return header;
    }

    private TwaDocAsnDetails createAsnLine(TwaDocAsnHeader header, PalletizeChangeData palletizeData, TwmBasMaterial material, LocationLineDto loc, TaskActionDto actionDto) {
        return this.createAsnLine(header, palletizeData, material, loc, palletizeData.getQuantity(), palletizeData.getUdf07(), actionDto);
    }

    private TwaDocAsnDetails createAsnLine(TwaDocAsnHeader header, PalletizeChangeData palletizeData, TwmBasMaterial material, LocationLineDto loc, BigDecimal quantity, String xwmsLotnumber, TaskActionDto actionDto) {
        TwaDocAsnDetails line = null;
        if (header == null) {
            return line;
        }
        if (palletizeData == null) {
            return line;
        }
        if (material == null) {
            return line;
        }

        if ((quantity==null) || (quantity.compareTo(BigDecimal.ZERO)<=0)){
            quantity=palletizeData.getQuantity();
        }
        if (StringUtils.isNullOrBlank(xwmsLotnumber)){
            xwmsLotnumber=palletizeData.getUdf07();
        }
        try{
            line=new TwaDocAsnDetails();
            line.setHeaderId(header.getId());
            line.setLineNumber(this.asnDetailsService.nextLineNumber(header.getId()));
            line.setLineStatus(WmsConstants.ASN_STATUS_CREATE);
            line.setRefDocNumber(null);
            line.setRefLineNumber(null);
            line.setMaterialId(material.getId());
            line.setMaterialCode(material.getCode());
            line.setMaterialName(material.getName());

            line.setQtyOrdered(quantity);
            line.setQtyOrderedEach(line.getQtyOrdered());
            line.setQtyPalletized(quantity);
            line.setQtyPalletizedEach(line.getQtyPalletized());
            line.setQtyReceived(BigDecimal.ZERO);
            line.setQtyReceivedEach(line.getQtyReceived());
            line.setQtyRejected(BigDecimal.ZERO);
            line.setQtyRejectedEach(line.getQtyRejected());
            line.setPackId(material.getPackId());
            line.setUomCode(material.getReceiveUom());
            line.setContainNumber(palletizeData.getContainnumber());
            line.setTraceNumber(palletizeData.getTracenumber());
            line.setOverReceiveFlag(CodesConstants.COMMON_FLAG_NO);
            line.setReceiveLocId(loc.getLocationId());
            line.setReceiveLocCode(loc.getLocationCode());
            line.setTotalPrice(BigDecimal.ZERO);
            line.setTotalCubic(BigDecimal.ZERO);
            line.setTotalGrossweight(BigDecimal.ZERO);
            line.setTotalNetweight(BigDecimal.ZERO);
            line.setTotalPrice(BigDecimal.ZERO);
            line.setProductStatus(null);
            line.setProductStatusDescr(null);
            line.setReleaseStatus(CodesConstants.COMMON_RELEASE_STATUS_CREATED);
            line.setReserveStatus(null);
            line.setFirstReceiveTime(header.getFirstReceiveTime());
            line.setLastReceiveTime(null);

            line.setLotattr05(palletizeData.getLotattr05());
            line.setLotattr06(palletizeData.getLotattr06());
            line.setLotattr07(palletizeData.getLotattr07());

            line.setUdf01(palletizeData.getUdf01());
            line.setUdf02(palletizeData.getUdf02());
            line.setUdf03(palletizeData.getUdf03());
            line.setUdf04(palletizeData.getUdf04());
            line.setUdf05(palletizeData.getUdf05());
            line.setUdf06(palletizeData.getUdf06());
            line.setUdf07(palletizeData.getUdf07());
            line.setUdf08(palletizeData.getUdf08());
            line.setUdf09(palletizeData.getUdf09());
            line.setUdf10(palletizeData.getUdf10());

            line.setDEdi01(null);
            line.setDEdi02(null);
            line.setDEdi03(null);
            line.setDEdi04(null);
            line.setDEdi05(null);
            line.setDEdi06(InforWasXcmgExchangeConstants.TASK_TYPE_PUTAWAY);
            line.setDEdi07(xwmsLotnumber);
            line.setDEdi08(null);
            line.setDEdi09(null);
            line.setDEdi10(null);
            line.setDEdi11(null);
            line.setDEdi12(null);
            line.setDEdi13(null);
            line.setDEdi14(null);
            line.setDEdi15(null);
            line.setDEdi16(null);
            line.setDEdi17(null);
            line.setDEdi18(null);
            line.setDEdi19(null);
            line.setDEdi20(null);
            line.setDelFlag(false);
            line.setNotes(null);

            line.setCreatedBy(header.getCreatedBy());
            line.setCreatedDate(new Date());
            line.setLastModifiedBy(line.getCreatedBy());
            line.setLastModifiedDate(line.getCreatedDate());
        }catch (Exception e){
            e.printStackTrace();
        }
        return line;
    }

    private TwaDocAsnDetails createAsnLine(TwaDocAsnHeader header, XwmsInventoryLineDto palletizeData, TwmBasMaterial material, LocationLineDto loc, BigDecimal quantity, String xwmsLotnumber, TaskActionDto actionDto) {
        TwaDocAsnDetails line = null;
        if (header == null) {
            return line;
        }
        if (palletizeData == null) {
            return line;
        }
        if (material == null) {
            return line;
        }

        if ((quantity==null) || (quantity.compareTo(BigDecimal.ZERO)<=0)){
            quantity=palletizeData.getStorageqty();
            if ((palletizeData.getPalqty()!=null) && (palletizeData.getPalqty().compareTo(BigDecimal.ZERO)>0)){
                quantity=quantity.subtract(palletizeData.getPalqty());
            }
            if ((quantity==null) || (quantity.compareTo(BigDecimal.ZERO))<=0){
                return line;
            }
        }
        if (StringUtils.isNullOrBlank(xwmsLotnumber)){
            xwmsLotnumber=palletizeData.getUdf07();
        }
        try{
            line=new TwaDocAsnDetails();
            line.setHeaderId(header.getId());
            line.setLineNumber(this.asnDetailsService.nextLineNumber(header.getId()));
            line.setLineStatus(WmsConstants.ASN_STATUS_CREATE);
            line.setRefDocNumber(null);
            line.setRefLineNumber(null);
            line.setMaterialId(material.getId());
            line.setMaterialCode(material.getCode());
            line.setMaterialName(material.getName());

            line.setQtyOrdered(quantity);
            line.setQtyOrderedEach(line.getQtyOrdered());
            line.setQtyPalletized(quantity);
            line.setQtyPalletizedEach(line.getQtyPalletized());
            line.setQtyReceived(BigDecimal.ZERO);
            line.setQtyReceivedEach(line.getQtyReceived());
            line.setQtyRejected(BigDecimal.ZERO);
            line.setQtyRejectedEach(line.getQtyRejected());
            line.setPackId(material.getPackId());
            line.setUomCode(material.getReceiveUom());
            line.setContainNumber(palletizeData.getContainernumber());
            line.setTraceNumber(palletizeData.getTracenumber());
            line.setOverReceiveFlag(CodesConstants.COMMON_FLAG_NO);
            line.setReceiveLocId(loc.getLocationId());
            line.setReceiveLocCode(loc.getLocationCode());
            line.setTotalPrice(BigDecimal.ZERO);
            line.setTotalCubic(BigDecimal.ZERO);
            line.setTotalGrossweight(BigDecimal.ZERO);
            line.setTotalNetweight(BigDecimal.ZERO);
            line.setTotalPrice(BigDecimal.ZERO);
            line.setProductStatus(null);
            line.setProductStatusDescr(null);
            line.setReleaseStatus(CodesConstants.COMMON_RELEASE_STATUS_CREATED);
            line.setReserveStatus(null);
            line.setFirstReceiveTime(header.getFirstReceiveTime());
            line.setLastReceiveTime(null);

            line.setLotattr05(palletizeData.getLotattr05());
            line.setLotattr06(palletizeData.getLotattr06());
            line.setLotattr07(palletizeData.getLotattr07());

            line.setUdf01(palletizeData.getUdf01());
            line.setUdf02(palletizeData.getUdf02());
            line.setUdf03(palletizeData.getUdf03());
            line.setUdf04(palletizeData.getUdf04());
            line.setUdf05(palletizeData.getUdf05());
            line.setUdf06(palletizeData.getUdf06());
            line.setUdf07(palletizeData.getUdf07());
            line.setUdf08(palletizeData.getUdf08());
            line.setUdf09(palletizeData.getUdf09());
            line.setUdf10(palletizeData.getUdf10());

            line.setDEdi01(null);
            line.setDEdi02(null);
            line.setDEdi03(null);
            line.setDEdi04(null);
            line.setDEdi05(null);
            line.setDEdi06(InforWasXcmgExchangeConstants.TASK_TYPE_PUTAWAY);
            line.setDEdi07(xwmsLotnumber);
            line.setDEdi08(null);
            line.setDEdi09(null);
            line.setDEdi10(null);
            line.setDEdi11(null);
            line.setDEdi12(null);
            line.setDEdi13(null);
            line.setDEdi14(null);
            line.setDEdi15(null);
            line.setDEdi16(null);
            line.setDEdi17(null);
            line.setDEdi18(null);
            line.setDEdi19(null);
            line.setDEdi20(null);
            line.setDelFlag(false);
            line.setNotes(null);

            line.setCreatedBy(header.getCreatedBy());
            line.setCreatedDate(new Date());
            line.setLastModifiedBy(line.getCreatedBy());
            line.setLastModifiedDate(line.getCreatedDate());
        }catch (Exception e){
            e.printStackTrace();
        }
        return line;
    }


/**==================================================================================================================**/
// ---- FUNC/X/OUTBOUND
/**==================================================================================================================**/
//
    private String allocate(TwaDocWaveHeader header, String batchnum, String worker, List<TwtActAllocationList> newAllocations){

        String m="";
        if (header==null){
            m="请指定波次进行分配.";
            return m;
        }
        m = this.allocationService.allocateCan(header, header.getId());
        if (!StringUtils.isNullOrBlank(m)){
            return m;
        }
        AllocationActionDto actionDto=null;
        List<TwtActAllocationList> allocations=null;
        try{
            actionDto = new AllocationActionDto();
            actionDto.setWaveRequire(CodesConstants.COMMON_FLAG_YES);
            if (StringUtils.isNullOrBlank(batchnum)){
                batchnum = TextUtils.genBatchNumber();
            }
            //
            actionDto.setWaveRequire(CodesConstants.COMMON_FLAG_YES);
            actionDto.setReleaseStatus(CodesConstants.COMMON_RELEASE_STATUS_CREATED);
            actionDto.setPackAllocateMode(CodesConstants.COMMON_FLAG_NO);
            actionDto.setPreAllocateMode(CodesConstants.COMMON_FLAG_NO);
            actionDto.setDockNumber(header.getDockNumber());
            actionDto.setWorker(worker);

            allocations = this.allocationService.allocate(batchnum, header.getDocumentNumber(), "",  actionDto);
            if ((allocations!=null) && (newAllocations!=null)) {
                newAllocations.clear();
                newAllocations.addAll(allocations);
            }
            if ((allocations==null)||(allocations.size()==0)) {
                if ((actionDto!=null) && (!StringUtils.isNullOrBlank(actionDto.getErrorText()))){
                    m=actionDto.getErrorText();
                }
                if (StringUtils.isNullOrBlank(m)){
                    m="请确认是否存在可用库存.";
                }
                m="分配失败:"+m;
            }
        }catch (Exception e){
            m="执行波次分配出错.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    private String shipmentByTasks(List<TwtActTaskList> tasks, String containNumber, String worker){
        String m = "";
        if ((tasks==null)||(tasks.size()==0)){
            m="找不到拣货任务,请确认是否已经发货.";
            return m;
        }
        if (StringUtils.isNullOrBlank(worker)){
            worker=SecurityUtils.getLoginUsername();
        }
        //check
        int size=0;
        if (!StringUtils.isNullOrBlank(containNumber)){
            containNumber=containNumber.trim();
            for (TwtActTaskList t1:tasks) {
                if (t1 == null) {
                    continue;
                }
                if (this.closed(t1)){
                    continue;
                }
                if (!containNumber.equalsIgnoreCase(t1.getFromTraceNumber())){
                    m="发货发生异常,托盘码数据不一致.任务:"+t1.getFromTraceNumber()+",发货:"+containNumber;
                    return m;
                }
                size++;
            }
        }
        if (size==0){
            return m;
        }
        String divisioncode=null;
        TaskReportData taskReport=null;
        //List<TaskReportData> taskReports=new ArrayList<>();
        try{
            for (TwtActTaskList t:tasks){
                if (t==null){
                    continue;
                }
                if (this.closed(t)){
                    continue;
                }
                if (StringUtils.isNullOrBlank(divisioncode)){
                    divisioncode=this.divisionService.retrieve(t.getDivisionId());
                }
                //taskReport=this.inforCommonWorkService.translateTo(divisioncode, t);
                m=this.shipmentByTask(t, worker);
                /**
                if ((StringUtils.isNullOrBlank(m))
                        && (InforWasXcmgExchangeConstants.SYS_XWMS.equalsIgnoreCase(t.getTaskSchema()))){
                    taskReports.add(taskReport);
                }
                 **/
                if (!StringUtils.isNullOrBlank(m)){
                    break;
                }
            }
            /**
            if ((taskReports!=null)&&(taskReports.size()>0)){
                this.sendWasTransReportToXwms(divisioncode, taskReports);
            }
             **/
        }catch (Exception e){
            m="执行发货失败.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    private String shipmentByTask(TwtActTaskList task, String worker){
        String m = "";
        if (StringUtils.isNullOrBlank(worker)){
            worker=SecurityUtils.getLoginUsername();
        }
        TaskChangeActionDto taskChangeActionDto = new TaskChangeActionDto();
        taskChangeActionDto.setWorkMode(WmsConstants.PICK_TASK_FIN_MODE_PICK);
        taskChangeActionDto.setWorkType(WmsConstants.PICKUP_MODE_PICKUP);
        taskChangeActionDto.setWorker(worker);
        if (transBuilder!=null){
            transBuilder.open();
        }
        m = this.taskService.finish(task, this.transBuilder, taskChangeActionDto);
        return m;
    }


/**==================================================================================================================**/
// ---- FUNC/X/INVENTORY
/**==================================================================================================================**/
//


/**==================================================================================================================**/
// ---- FUNC/X/TRANS
/**==================================================================================================================**/

    private String createEdiTrans(List<Long> transIds, String worker){
        String m = "";
        if ((transIds==null)||(transIds.size()==0)){
            m="请指定交易生成接口数据";
            return m;
        }
        if (StringUtils.isNullOrBlank(worker)){
            worker=SecurityUtils.getLoginUsername();
        }
        TwtActTransList tran=null;
        List<TwtActTransList> trans=null;
        TwiActTransList etran=null;
        List<TwiActTransList> etrans=null;
        try{
            for (Long tid:transIds){
                if (tid==null){
                    continue;
                }
                etrans=this.dyncdataQueryService.queryEdiTransByTransId(tid);
                if ((etrans!=null)&& (etrans.size()>0)){
                    m="已经生成接口数据.交易ID:"+String.valueOf(tid);
                    return m;
                }
                tran=this.transService.findById(tid);
                if (tran==null){
                    m="找不到交易数据.ID:"+String.valueOf(tid);
                    return m;
                }
                etran=this.translateTo(tran, worker);
                if (etran!=null){
                    this.ediTransactionService.save(etran);
                }
            }
        }catch (Exception e){
            m="生成接口数据异常.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }

    private String createEdiTrans(TwtActTransList trans, String errorText, String worker){
        String m = "";
        if (trans==null){
            m="请指定交易生成接口数据";
            return m;
        }
        if (StringUtils.isNullOrBlank(worker)){
            worker=SecurityUtils.getLoginUsername();
        }
        TwiActTransList etran=null;
        List<TwiActTransList> etrans=null;
        try{
            etrans=this.dyncdataQueryService.queryEdiTransByTransId(trans.getId());
            if ((etrans!=null)&& (etrans.size()>0)){
                m="已经生成接口数据.交易号:"+trans.getNumber();
                return m;
            }
            if (!StringUtils.isNullOrBlank(trans.getUdf11())){
                if ((!InforWasXcmgExchangeConstants.SYS_XWMS.equalsIgnoreCase(trans.getUdf11()))
                            && ((!CodesConstants.SYSTEM_MES.equalsIgnoreCase(trans.getUdf11())))
                            && ((!CodesConstants.SYSTEM_ERP.equalsIgnoreCase(trans.getUdf11()))) ){
                    //
                    m="非对接系统创建,不用回传.交易号:"+trans.getNumber();
                    return m;
                }
            }

            if (!StringUtils.isNullOrBlank(errorText)){
                etran=this.translateTo(trans, worker, CodesConstants.COMMON_STATUS_APP_ERROR, errorText);
            }else {
                etran=this.translateTo(trans, worker);
                etran.setEdiReceiveTime(new Date());
                etran.setEdiReceiveStatus(CodesConstants.COMMON_STATUS_CLOSED);
                etran.setEdiReceiveMessage(null);
            }
            if (etran!=null){
                this.ediTransactionService.save(etran);
            }
        }catch (Exception e){
            m="生成接口数据异常.异常:"+e.getMessage();
            e.printStackTrace();
        }
        return m;
    }



/**==================================================================================================================**/
// ---- FUNC/X/COMMON
/**==================================================================================================================**/

    private String nextLineNumber(int linenum){
        Integer nextlinenum = Integer.valueOf((new Double(Math.ceil((double)linenum / 10.0D) + 1.0D)).intValue() * 10);
        return StringUtils.lpad(String.valueOf(nextlinenum), "0", 4L);
    }

    private String palletizeCheck(XwmsInventoryLineDto palletizeData){
        String m = XcmgAmSupport.check(palletizeData);

        if (StringUtils.isNullOrBlank(m)){
            return m;
        }
        List<TwaInventoryDetails> storages=null;
        List<TwtActTaskList> tasks=null;
        try{
            storages=this.inventoryService.findByContainNumber(palletizeData.getContainernumber());
            if ((storages!=null) && (storages.size()>0)){
                m="托盘已经存在库存,请确认托盘码是否重复.托盘码:"+palletizeData.getContainernumber();
                return m;
            }
            tasks=this.taskService.queryWorkingTasks("", palletizeData.getContainernumber());
            if ((storages!=null) && (storages.size()>0)){
                m="托盘正在作业中,请确认托盘码是否重复.托盘码:"+palletizeData.getContainernumber();
                return m;
            }
        }catch (Exception e){
            e.printStackTrace();
            m="校验码盘数据异常.异常:"+e.getMessage();
        }
        return m;
    }

    private String palletizeCheck(PalletizeChangeData palletizeData){
        String m = XcmgAmSupport.check(palletizeData);

        if (!StringUtils.isNullOrBlank(m)){
            return m;
        }
        List<TwaInventoryDetails> storages=null;
        List<TwtActTaskList> tasks=null;
        try{
            storages=this.inventoryService.findByContainNumber(palletizeData.getContainnumber());
            if ((storages!=null) && (storages.size()>0)){
                m="托盘已经存在库存,请确认托盘码是否重复.托盘码:"+palletizeData.getContainnumber();
                return m;
            }
            tasks=this.taskService.queryWorkingTasks("", palletizeData.getContainnumber());
            if ((storages!=null) && (storages.size()>0)){
                m="托盘正在作业中,请确认托盘码是否重复.托盘码:"+palletizeData.getContainnumber();
                return m;
            }
        }catch (Exception e){
            e.printStackTrace();
            m="校验码盘数据异常.异常:"+e.getMessage();
        }
        return m;
    }

    private boolean checkAllocate(TwtActAllocationList details){
        if (details==null){
            return false;
        }
        if (!StringUtils.isNullOrBlank(details.getStatus())){
            if (details.getStatus().compareTo(WmsConstants.SO_STATUS_SHIP)>=0){
                return false;
            }
        }
        if (StringUtils.isNullOrBlank(details.getFromTraceNumber())){
            return false;
        }
        if (!MathUtils.validQuantity(details.getQtyEach())){
            return false;
        }
        return true;
    }

    private WaveShipLineDto translateTo(TwtActAllocationList pick, Map<Long, TwmBasMaterial> materials, Map<Long, TwaDocWaveHeader> headers){
        WaveShipLineDto data=new WaveShipLineDto();

        data.setId(String.valueOf(pick.getId()));
        data.setTransactionid(String.valueOf(pick.getId()));
        data.setVersion(pick.getVersion());
        data.setLinesequence(pick.getDocLinenumber());
        TwmBasMaterial mat=materials.get(pick.getMaterialId());
        if (mat==null){
            mat=materialService.findById(pick.getMaterialId());
            if (mat==null){
                return null;
            }
            materials.put(pick.getMaterialId(), mat);
        }
        if (mat!=null){
            data.setMaterialcode(mat.getCode());
            data.setMaterialname(mat.getName());
        }
        data.setQuantity(pick.getQty());
        data.setQuantityeach(pick.getQtyEach());
        //
        data.setUom(pick.getUomCode());
        data.setWorking(CodesConstants.DATA_WORKING_QUERY);
        data.setWorkmode("");
        data.setDocumentnumber(pick.getDocNumber());
        data.setDocumentlinenumber(pick.getDocLinenumber());
        data.setLotnumber(pick.getLotNumber());
        data.setTracenumber(pick.getFromTraceNumber());
        data.setContainnumber(pick.getFromContainNumber());
        data.setFromlocationcode(this.locationResolver.check(pick.getFromLocId()));
        data.setQuantity(pick.getQty());
        data.setQuantityeach(pick.getQtyEach());
        data.setTotracenumber(pick.getToTraceNumber());
        data.setTocontainnumber(pick.getToContainNumber());
        data.setTolocationcode(this.locationResolver.check(pick.getToLocId()));
        if ((StringUtils.isNullOrBlank(data.getTolocationcode()))
                && (pick.getPlantoLocId()!=null)){
            data.setTolocationcode(this.locationResolver.check(pick.getPlantoLocId()));
        }

        TwaDocWaveHeader header=null;
        if (pick.getWaveId()!=null){
            header = headers.get(pick.getWaveId());
        }
        if ((header==null) && (pick.getDocId()!=null)){
            header = headers.get(pick.getWaveId());
        }

        if (header!=null){
            data.setPlantoplace(header.getPickLocationCode());
            data.setDeliveryinfo(header.getNotes());
            if ((!StringUtils.isNullOrBlank(data.getDeliveryinfo())) && (data.getDeliveryinfo().trim().length()>30)){
                data.setDeliveryinfo(data.getDeliveryinfo().substring(0,30)+"....");
            }
        }
        //
        if (!StringUtils.isNullOrBlank(pick.getUdf09())){
            data.setDeliveryinfo(pick.getUdf09().trim());
        }
        data.setLinestatus(pick.getStatus());
        //data.setLinestatusname(this.getCodeName(WmsConstants.CODE_TYPE_SO_STATUS, pick.getStatus()));
        data.setCreatetime(DateUtils.format(pick.getCreatedDate(),DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS));
        data.setCreateby(pick.getCreatedBy());
        return data;
    }

    private CounWorkLineDto translateTo(TwtActTaskList task, Map<Long, TwmBasMaterial> materials, Map<Long, TwaDocCoHeader> headers){
        CounWorkLineDto data=new CounWorkLineDto();

        data.setId(String.valueOf(task.getId()));
        data.setTransactionid(String.valueOf(task.getId()));
        data.setVersion(task.getVersion());
        data.setLinesequence(task.getDocLinenumber());
        TwmBasMaterial mat=materials.get(task.getMaterialId());
        if (mat==null){
            mat=materialService.findById(task.getMaterialId());
            if (mat==null){
                return null;
            }
            materials.put(task.getMaterialId(), mat);
        }
        if (mat!=null){
            data.setMaterialcode(mat.getCode());
            data.setMaterialname(mat.getName());
        }
        data.setQuantity(task.getFromQty());
        data.setQuantityeach(task.getFromQtyEach());
        //
        data.setUom(task.getFromUomCode());
        data.setWorking(CodesConstants.DATA_WORKING_QUERY);
        data.setWorkmode("");
        data.setDocumentnumber(task.getDocNumber());
        data.setDocumentlinenumber(task.getDocLinenumber());
        data.setLotnumber(task.getLotattr05());
        data.setTracenumber(task.getFromTraceNumber());
        data.setContainnumber(task.getFromContainNumber());
        data.setQuantity(task.getFromQty());
        data.setQuantityeach(task.getFromQtyEach());

        TwaDocCoHeader header=null;
        if (task.getDocId()!=null){
            header = headers.get(task.getDocId());
        }
        if (header!=null){
        }
        data.setLinestatus(task.getStatus());
        //data.setLinestatusname(this.getCodeName(WmsConstants.CODE_TYPE_SO_STATUS, pick.getStatus()));
        data.setCreatetime(DateUtils.format(task.getCreatedDate(),DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS));
        data.setCreateby(task.getCreatedBy());
        return data;
    }

    private TwiActTransList translateTo(TwtActTransList trans, String worker){
        TwiActTransList ediTrans=null;
        if (trans==null){
            return ediTrans;
        }
        try{
            ediTrans=new TwiActTransList();
            ediTrans=new TwiActTransList();
            ediTrans.setGlobalClientid(trans.getGlobalClientId());
            ediTrans.setDivisionId(trans.getDivisionId());
            ediTrans.setCustomerId(trans.getCustomerId());
            ediTrans.setBatchnumber(trans.getBatchNumber());
            ediTrans.setRefid(String.valueOf(trans.getId()));
            ediTrans.setTransNumber(trans.getNumber());
            ediTrans.setTransType(trans.getType());
            ediTrans.setMaterialId(trans.getMaterialId());
            ediTrans.setMaterialCode(trans.getMaterialCode());
            ediTrans.setMaterialName(trans.getMaterialName());
            ediTrans.setMaterialNameEn(trans.getMaterialNameEn());
            ediTrans.setDocumentId(trans.getDocId());
            ediTrans.setDocumentDetailsId(trans.getDocDetailsId());
            ediTrans.setGroupId(null);
            ediTrans.setGroupDetailsId(null);
            ediTrans.setDocumentNumber(trans.getDocNumber());
            ediTrans.setDocumentLineNumber(trans.getDocLinenumber());
            ediTrans.setDocumentCategory(trans.getCategory());
            ediTrans.setDocumentType(trans.getDocType());
            ediTrans.setRefDocumentNumber(trans.getRefDocNumber());
            ediTrans.setRefDocumentLineNumber(trans.getRefDocLinenumber());
            ediTrans.setGroupNumber(null);
            ediTrans.setGroupLineNumber(null);
            ediTrans.setStatus(CodesConstants.COMMON_STATUS_CLOSED);
            ediTrans.setCustomerCode(null);
            ediTrans.setSupplierCode(trans.getFromLotattr06());
            ediTrans.setCarrierCode(null);
            ediTrans.setConsigneeCode(null);
            ediTrans.setToDivisionCode(null);
            ediTrans.setToCustomerCode(null);  //trans.getCustomerCode()
            ediTrans.setToMaterialCode(trans.getMaterialCode());
            ediTrans.setPackType(null);
            ediTrans.setUomCode(trans.getUomCode());
            ediTrans.setQtyOrdered(trans.getQtyOrdered());
            ediTrans.setQtyOrderedEach(ediTrans.getQtyOrdered());
            ediTrans.setQtyTrans(trans.getQtyTrans());
            ediTrans.setQtyTransEach(ediTrans.getQtyTrans());
            ediTrans.setFromQtyTrans(trans.getFromQtyTrans());
            ediTrans.setFromQtyTransEach(ediTrans.getFromQtyTrans());
            ediTrans.setToQtyTrans(trans.getToQtyTrans());
            ediTrans.setToQtyTransEach(ediTrans.getToQtyTrans());
            ediTrans.setTotalPrice(trans.getTotalPrice());
            ediTrans.setTotalCubic(trans.getTotalCubic());
            ediTrans.setTotalGrossweight(trans.getTotalGrossweight());
            ediTrans.setTotalNetweight(trans.getTotalNetweight());
            ediTrans.setToUomCode(trans.getToUomCode());
            ediTrans.setFromLotNumber(trans.getFromLotattr07());
            ediTrans.setToLotNumber(trans.getToLotnoNumber());
            ediTrans.setFromZoneCode(null);
            ediTrans.setToZoneCode(null);
            ediTrans.setFromLocationCode(trans.getFromLocCode());
            ediTrans.setToLocationCode(trans.getToLocCode());
            ediTrans.setFromTraceNumber(trans.getFromTraceNumber());
            ediTrans.setToTraceNumber(trans.getToTraceNumber());
            ediTrans.setFromContainNumber(trans.getFromContainNumber());
            ediTrans.setToContainNumber(trans.getToContainNumber());
            ediTrans.setRefTaskNumber(trans.getCallNumber());
            ediTrans.setRefType(WmsConstants.REF_TYPE_TRANS);
            ediTrans.setRefNumber(trans.getNumber());
            ediTrans.setUdf01(trans.getUdf01());
            ediTrans.setUdf02(trans.getUdf02());
            ediTrans.setUdf03(trans.getUdf03());
            ediTrans.setUdf04(trans.getUdf04());
            ediTrans.setUdf05(trans.getUdf05());
            ediTrans.setUdf06(trans.getUdf06());
            ediTrans.setUdf07(trans.getUdf07());
            ediTrans.setUdf08(trans.getUdf08());
            ediTrans.setUdf09(trans.getUdf09());
            ediTrans.setUdf10(trans.getUdf10());
            ediTrans.setUdf11(trans.getUdf11());
            ediTrans.setUdf12(trans.getUdf12());
            ediTrans.setUdf13(trans.getUdf13());
            ediTrans.setUdf14(trans.getUdf14());
            ediTrans.setUdf15(trans.getUdf15());
            ediTrans.setUdf16(trans.getUdf16());
            ediTrans.setUdf17(trans.getUdf17());
            ediTrans.setUdf18(trans.getUdf18());
            ediTrans.setUdf19(trans.getUdf19());
            ediTrans.setUdf20(trans.getUdf20());

            ediTrans.setEdiSendPrior(WmsConstants.TASK_PRIOR_NORMAL);
            ediTrans.setEdiSendTime(null);
            ediTrans.setEdiSendStatus(null);
            ediTrans.setEdiSendMessage(null);
            ediTrans.setEdiReceiveTime(new Date());
            ediTrans.setEdiReceiveStatus(null);
            ediTrans.setEdiReceiveMessage(null);
            ediTrans.setRetryTimes(0);
            ediTrans.setNotes(trans.getNotes());
            ediTrans.setCreatedDate(new Date());
            ediTrans.setCreatedBy(trans.getLastModifiedBy());
            ediTrans.setLastModifiedDate(ediTrans.getCreatedDate());
            ediTrans.setLastModifiedBy(ediTrans.getCreatedBy());
        }catch (Exception e){
            e.printStackTrace();
        }
        return ediTrans;
    }

    private TwiActTransList translateTo(TwtActTransList trans, String worker, String returnCode, String returnText) {
        TwiActTransList  ediTrans = this.translateTo(trans, worker);
        this.updateEdiTransData(ediTrans, worker, returnCode, returnText);
        return ediTrans;
    }

    private String updateEdiTransData(TwiActTransList ediTrans, String worker, String returnCode, String returnText){
        String m = "";
        if (ediTrans==null){
            return m;
        }
        if (StringUtils.isNullOrBlank(worker)){
            worker=SecurityUtils.getLoginUsername();
        }
        if (StringUtils.isNullOrBlank(returnCode)){
            returnCode=CodesConstants.COMMON_STATUS_CLOSED;
            if (!StringUtils.isNullOrBlank(returnText)){
                returnCode = InforWasXcmgExchangeConstants.RESULT_CODE_EDI_ERROR;
            }
        }
        if ((CodesConstants.COMMON_STATUS_APP_ERROR.equalsIgnoreCase(returnCode))
                || (CodesConstants.COMMON_STATUS_SYS_ERROR.equalsIgnoreCase(returnCode))
                || (CodesConstants.COMMON_FLAG_NO.equalsIgnoreCase(returnCode))){
            ediTrans.setStatus(InforWasXcmgExchangeConstants.RESULT_CODE_EDI_ERROR);
        }else{
            ediTrans.setStatus(CodesConstants.COMMON_STATUS_CLOSED);
        }
        ediTrans.setEdiSendTime(new Date());
        ediTrans.setEdiSendStatus(CodesConstants.COMMON_STATUS_CLOSED);
        ediTrans.setEdiSendMessage(null);
        ediTrans.setEdiReceiveTime(new Date());
        ediTrans.setEdiReceiveStatus(returnCode);
        ediTrans.setEdiReceiveMessage(returnText);
        ediTrans.setLastModifiedDate(new Date());
        ediTrans.setLastModifiedBy(worker);
        return m;
    }

    private String updateEdiTransData(TwtActTransList trans, String worker, String returnText){
        String m = "";
        if (StringUtils.isNullOrBlank(returnText)){
            m = this.updateEdiTransData(trans, worker, CodesConstants.COMMON_STATUS_CLOSED, null);
        }else{
            m = this.updateEdiTransData(trans, worker, CodesConstants.COMMON_STATUS_APP_ERROR, returnText);
        }
        return m;
    }

    private String updateEdiTransData(TwtActTransList trans, String worker, String returnCode, String returnText){
        String m = "";
        if (trans==null){
            return m;
        }
        if (StringUtils.isNullOrBlank(returnCode)){
            returnCode=CodesConstants.COMMON_STATUS_CLOSED;
        }
        if (StringUtils.isNullOrBlank(worker)){
            worker=SecurityUtils.getLoginUsername();
        }
        trans.setEdiSendTime(new Date());
        trans.setEdiSendStatus(CodesConstants.COMMON_STATUS_CLOSED);
        trans.setEdiReceiveTime(new Date());
        trans.setEdiReceiveStatus(returnCode);
        trans.setEdiReceiveMsg(returnText);
        trans.setLastModifiedDate(new Date());
        trans.setLastModifiedBy(worker);
        return m;
    }

    private String populate(LedMessageData source, TblLedMessage target){
        String m = "";

        if (source==null){
            return m;
        }
        if (target==null){
            return m;
        }
        //target.setId(source.getId());
        //target.setDivisionId(source.getDivisionid());
        target.setType(source.getType());
        //target.setCode(source.getCode());
        //target.setIp(source.getIp());
        target.setBizType(source.getBizType());
        target.setPalletCode(source.getPalletCode());
        target.setTaskCode(source.getTaskCode());
        target.setMatCode(source.getMatCode());
        target.setMessage(source.getMessage());
        target.setQuantity(source.getQuantity());
        target.setUnit(source.getUnit());
        target.setLineCode(source.getLineCode());
        target.setStation(source.getStation());
        target.setStocktaking(source.getStocktaking());
        target.setDf1(source.getDf1());
        target.setDf2(source.getDf2());
        target.setDf3(source.getDf3());
        target.setDf4(source.getDf4());
        //target.setStatus(source.getStatus());
        //target.setLedStatus(source.getLedStatus());
        return m;
    }

    public TwmBasMaterial loadMaterial(StorageLineResultDto xwmsInventory){
        TwmBasMaterial material=null;
        if (xwmsInventory==null){
            return material;
        }
        if (StringUtils.isNullOrBlank(xwmsInventory.getSku())){
            return material;
        }
        try{
            material=new TwmBasMaterial();

            material.setGlobalClientId(XcmgAmConstants.CLIENT_ID_XCMG);
            material.setCustomerId(XcmgAmConstants.CUSTOMER_ID_XCMG_AM);

            material.setCode(xwmsInventory.getSku().trim());
            material.setName(material.getCode());
            if (!StringUtils.isNullOrBlank(xwmsInventory.getDescr())){
                material.setName(xwmsInventory.getDescr().trim());
            }
            material.setNameEn(material.getName());
            material.setType("PART");
            material.setCategory("PART");

            material.setStatus(CodesConstants.COMMON_STATUS_CREATED);
            material.setEasyCode(null);
            material.setEasyName(null);
            material.setCycleClass("A");
            material.setSpecModel(null);
            material.setFeatureCode(null);
            material.setMaterialClass(null);
            material.setFreightClass(null);
            material.setRegulateFlag(null);
            material.setReceiveUom(CodesConstants.UOM_EACH);
            material.setShipUom(CodesConstants.UOM_EACH);
            material.setPrintUom(CodesConstants.UOM_EACH);
            if (!StringUtils.isNullOrBlank(xwmsInventory.getUom())){
                material.setPrintUom(xwmsInventory.getUom().trim());
            }

            material.setPackId(1000100100010L);
            material.setParuleId(1000100100010L);
            //
            material.setAllocruleId(null);
            material.setStorageMaxQty(null);
            material.setStorageMinQty(null);
            material.setShelflifeDays(null);
            material.setExpireDays(null);
            material.setOverstorageDays(null);
            material.setAlertDays(null);
            material.setOverReceivingFlag(null);
            material.setHazardFlag(null);
            material.setPartFlag(null);
            material.setKitFlag(null);
            material.setMaterialWidth(null);
            material.setMaterialHeight(null);
            material.setMaterialPrice(null);
            material.setMaterialCubic(null);
            material.setMaterialGrossweight(null);
            material.setMaterialNetweight(null);
            material.setMaterialTareweight(null);

            material.setGroupCode01(null);
            material.setGroupCode02(null);
            material.setGroupCode03(null);
            material.setGroupCode04(null);
            material.setGroupCode05(null);
            material.setGroupCode06(null);
            material.setGroupCode07(null);
            material.setGroupCode08(null);
            material.setGroupCode09(null);
            material.setGroupCode10(null);
            material.setRefCode01(null);
            material.setRefCode02(null);
            material.setRefCode03(null);
            material.setRefCode04(null);
            material.setRefCode05(null);
            material.setUdf01(null);
            material.setUdf02(null);
            material.setUdf03(null);
            material.setUdf04(null);
            material.setUdf05(null);
            material.setUdf06(null);
            material.setUdf07(null);
            material.setUdf08(null);
            material.setUdf09(null);

            material.setUdf11(null);
            material.setUdf12(null);
            material.setUdf13(null);
            material.setUdf14(null);
            material.setUdf15(null);
            material.setUdf16(null);
            material.setUdf17(null);
            material.setUdf18(null);
            material.setUdf19(null);
            material.setUdf20(null);

            material.setEdi01(null);
            material.setEdi02(null);
            material.setEdi03(null);
            material.setEdi04(null);
            material.setEdi05(null);
            material.setEdi06(null);
            material.setEdi07(null);
            material.setEdi08(null);
            material.setEdi09(null);
            material.setEdi10(null);
            material.setEdi11(null);
            material.setEdi12(null);
            material.setEdi13(null);
            material.setEdi14(null);
            material.setEdi15(null);
            material.setEdi16(null);
            material.setEdi17(null);
            material.setEdi18(null);
            material.setEdi19(null);
            material.setEdi20(null);

            material.setEditable(true);
            material.setEnabled(true);
            material.setCreatedBy(SecurityUtils.getLoginUsername());
            material.setCreatedDate(new Date());
            material.setLastModifiedBy(material.getCreatedBy());
            material.setLastModifiedDate(material.getCreatedDate());
            this.materialService.save(material);

        }catch (Exception e){
            e.printStackTrace();
        }
        return material;
    }

    private TwmBasMaterial loadMaterial(TaskOrderDto taskOrder){
        TwmBasMaterial material=null;
        if (taskOrder==null){
            return material;
        }
        if (StringUtils.isNullOrBlank(taskOrder.getMCode())){
            return material;
        }
        try{
            material=new TwmBasMaterial();

            TwmBasPack pack=null;
            TwmRulePaHeader parule=null;
            TwmRuleAllocationHeader allocationrule=null;
            material.setGlobalClientId(XcmgAmConstants.CLIENT_ID_XCMG);
            material.setCustomerId(XcmgAmConstants.CUSTOMER_ID_XCMG_AM);

            material.setCode(taskOrder.getMCode().trim());
            material.setName(taskOrder.getGoodName().trim());
            if (StringUtils.isNullOrBlank(material.getName())){
                material.setName(material.getNameEn());
            }
            material.setNameEn(material.getName());
            material.setType("PART");
            material.setCategory("PART");

            material.setStatus(CodesConstants.COMMON_STATUS_CREATED);
            material.setEasyCode(null);
            material.setEasyName(null);
            material.setCycleClass("A");
            material.setSpecModel(null);
            material.setFeatureCode(null);
            material.setMaterialClass(null);
            material.setFreightClass(null);
            material.setRegulateFlag(null);
            material.setReceiveUom(CodesConstants.UOM_EACH);
            material.setShipUom(CodesConstants.UOM_EACH);
            material.setPrintUom(CodesConstants.UOM_EACH);
            if (StringUtils.isNullOrBlank(taskOrder.getUom())){
                material.setPrintUom(taskOrder.getUom().trim());
            }

            material.setPackId(1000100100010L);
            material.setParuleId(1000100100010L);
            //
            material.setAllocruleId(null);
            material.setStorageMaxQty(null);
            material.setStorageMinQty(null);
            material.setShelflifeDays(null);
            material.setExpireDays(null);
            material.setOverstorageDays(null);
            material.setAlertDays(null);
            material.setOverReceivingFlag(null);
            material.setHazardFlag(null);
            material.setPartFlag(null);
            material.setKitFlag(null);
            material.setMaterialWidth(null);
            material.setMaterialHeight(null);
            material.setMaterialPrice(null);
            material.setMaterialCubic(null);
            material.setMaterialGrossweight(null);
            material.setMaterialNetweight(null);
            material.setMaterialTareweight(null);

            material.setGroupCode01(null);
            material.setGroupCode02(null);
            material.setGroupCode03(null);
            material.setGroupCode04(null);
            material.setGroupCode05(null);
            material.setGroupCode06(null);
            material.setGroupCode07(null);
            material.setGroupCode08(null);
            material.setGroupCode09(null);
            material.setGroupCode10(null);
            material.setRefCode01(null);
            material.setRefCode02(null);
            material.setRefCode03(null);
            material.setRefCode04(null);
            material.setRefCode05(null);
            material.setUdf01(null);
            material.setUdf02(null);
            material.setUdf03(null);
            material.setUdf04(null);
            material.setUdf05(null);
            material.setUdf06(null);
            material.setUdf07(null);
            material.setUdf08(null);
            BigDecimal uomqty=null;
            material.setUdf09(null);


            material.setUdf11(null);
            material.setUdf12(null);
            material.setUdf13(null);
            material.setUdf14(null);
            material.setUdf15(null);
            material.setUdf16(null);
            material.setUdf17(null);
            material.setUdf18(null);

            BigDecimal qty=null;
            material.setUdf19(qty);
            material.setUdf20(qty);

            material.setEdi01(null);
            material.setEdi02(null);
            material.setEdi03(null);
            material.setEdi04(null);
            material.setEdi05(null);
            material.setEdi06(null);
            material.setEdi07(null);
            material.setEdi08(null);
            material.setEdi09(null);
            material.setEdi10(null);
            material.setEdi11(null);
            material.setEdi12(null);
            material.setEdi13(null);
            material.setEdi14(null);
            material.setEdi15(null);
            material.setEdi16(null);
            material.setEdi17(null);
            material.setEdi18(null);
            material.setEdi19(null);
            material.setEdi20(null);

            material.setEditable(true);
            material.setEnabled(true);
            material.setCreatedBy(SecurityUtils.getLoginUsername());
            material.setCreatedDate(new Date());
            material.setLastModifiedBy(material.getCreatedBy());
            material.setLastModifiedDate(material.getCreatedDate());
            this.materialService.save(material);

        }catch (Exception e){
            e.printStackTrace();
        }
        return material;
    }

    private String fullCheck(PutawayActionDto actionDto) {
        if (actionDto==null){
            return "";
        }
        StringBuffer buf=new StringBuffer();
        if ((actionDto.getCheckDivisionId()!=null) && (actionDto.getCheckDivisionId()>0L)){
            buf.append("and division_id=").append(String.valueOf(actionDto.getCheckDivisionId())).append(" ");
        }
        if ((actionDto.getCheckZoneIds()!=null) && (actionDto.getCheckZoneIds().size()>0)){
            buf.append("and zone_id in ").append(this.listLongValue(actionDto.getCheckZoneIds())).append(" ");
        }
        if ((actionDto.getCheckLayerNumbers()!=null) && (actionDto.getCheckLayerNumbers().size()>0)){
            buf.append("and z_coord in ").append(this.listIntValue(actionDto.getCheckLayerNumbers())).append(" ");
        }
        if ((actionDto.getCheckLocationGroups()!=null) && (actionDto.getCheckLocationGroups().size()>0)){
            buf.append("and location_group in ").append(this.listStringValue(actionDto.getCheckLocationGroups())).append(" ");
        }

        //
        if ((actionDto.getCheckHeight()!=null) && (actionDto.getCheckHeight().compareTo(BigDecimal.ZERO)>0)){
            buf.append("and location_height >= ").append(actionDto.getCheckHeight().stripTrailingZeros().toPlainString()).append(" ");
        }
        if ((actionDto.getCheckLength()!=null) && (actionDto.getCheckLength().compareTo(BigDecimal.ZERO))>0){
            buf.append("and location_len = ").append(actionDto.getCheckLength().stripTrailingZeros().toPlainString()).append(" ");
        }

        return buf.toString();
    }

    //
    private String listStringValue(List<String> texts){
        StringBuffer buf=new StringBuffer();
        buf.append("(");

        int index=0;
        for (String t:texts){
            index++;
            if (t==null){
                continue;
            }
            buf.append("'").append(t.trim()).append("'");
            if (index<texts.size()){
                buf.append(",");
            }
        }
        buf.append(")");
        return buf.toString();
    }

    private String listIntValue(List<Integer> values){
        StringBuffer buf=new StringBuffer();
        buf.append("(");

        int index=0;
        for (Integer v:values){
            index++;
            if ((v==null) || (v<=0)){
                continue;
            }
            buf.append("").append(String.valueOf(v)).append("");
            if (index<values.size()){
                buf.append(",");
            }
        }
        buf.append(")");
        return buf.toString();
    }

    private String listLongValue(List<Long> values){
        StringBuffer buf=new StringBuffer();
        buf.append("(");

        int index=0;
        for (Long v:values){
            index++;
            if ((v==null) || (v<=0)){
                continue;
            }
            buf.append("").append(String.valueOf(v)).append("");
            if (index<values.size()){
                buf.append(",");
            }
        }
        buf.append(")");
        return buf.toString();
    }

}
